From d6412f697dc26d4e080dc65c044272d9c867cbd7 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 14 Nov 2024 08:55:45 +0000 Subject: [PATCH 1/4] feat: add round-trip mode PiperOrigin-RevId: 696395696 Source-Link: https://github.com/googleapis/googleapis/commit/0a70c191e35505037daf9b97e908a0b76e650285 Source-Link: https://github.com/googleapis/googleapis-gen/commit/e441f0519236d8c8a7673aac1726a903c21836c5 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLW5ldHdvcmstbWFuYWdlbWVudC8uT3dsQm90LnlhbWwiLCJoIjoiZTQ0MWYwNTE5MjM2ZDhjOGE3NjczYWFjMTcyNmE5MDNjMjE4MzZjNSJ9 --- .../v1/.coveragerc | 13 + .../v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../reachability_service.rst | 10 + .../docs/network_management_v1/services_.rst | 6 + .../v1/docs/network_management_v1/types_.rst | 6 + .../cloud/network_management/__init__.py | 117 + .../cloud/network_management/gapic_version.py | 16 + .../google/cloud/network_management/py.typed | 2 + .../cloud/network_management_v1/__init__.py | 118 + .../network_management_v1/gapic_metadata.json | 118 + .../network_management_v1/gapic_version.py | 16 + .../cloud/network_management_v1/py.typed | 2 + .../services/__init__.py | 15 + .../services/reachability_service/__init__.py | 22 + .../reachability_service/async_client.py | 1597 ++++ .../services/reachability_service/client.py | 1917 +++++ .../services/reachability_service/pagers.py | 163 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../reachability_service/transports/base.py | 362 + .../reachability_service/transports/grpc.py | 660 ++ .../transports/grpc_asyncio.py | 751 ++ .../reachability_service/transports/rest.py | 1714 ++++ .../transports/rest_base.py | 588 ++ .../network_management_v1/types/__init__.py | 114 + .../types/connectivity_test.py | 735 ++ .../types/reachability.py | 293 + .../network_management_v1/types/trace.py | 3164 +++++++ .../v1/mypy.ini | 3 + .../v1/noxfile.py | 280 + ..._service_create_connectivity_test_async.py | 57 + ...y_service_create_connectivity_test_sync.py | 57 + ..._service_delete_connectivity_test_async.py | 56 + ...y_service_delete_connectivity_test_sync.py | 56 + ...ity_service_get_connectivity_test_async.py | 52 + ...lity_service_get_connectivity_test_sync.py | 52 + ...y_service_list_connectivity_tests_async.py | 53 + ...ty_service_list_connectivity_tests_sync.py | 53 + ...y_service_rerun_connectivity_test_async.py | 56 + ...ty_service_rerun_connectivity_test_sync.py | 56 + ..._service_update_connectivity_test_async.py | 55 + ...y_service_update_connectivity_test_sync.py | 55 + ...ata_google.cloud.networkmanagement.v1.json | 997 +++ .../fixup_network_management_v1_keywords.py | 181 + .../v1/setup.py | 99 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.13.txt | 7 + .../v1/testing/constraints-3.7.txt | 11 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/network_management_v1/__init__.py | 16 + .../test_reachability_service.py | 7462 +++++++++++++++++ 62 files changed, 22833 insertions(+) create mode 100644 owl-bot-staging/google-cloud-network-management/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-network-management/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-network-management/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-network-management/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json create mode 100644 owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/.coveragerc b/owl-bot-staging/google-cloud-network-management/v1/.coveragerc new file mode 100644 index 000000000000..20f78aac3034 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/network_management/__init__.py + google/cloud/network_management/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-network-management/v1/.flake8 b/owl-bot-staging/google-cloud-network-management/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in b/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in new file mode 100644 index 000000000000..240002b7c5c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/network_management *.py +recursive-include google/cloud/network_management_v1 *.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/README.rst b/owl-bot-staging/google-cloud-network-management/v1/README.rst new file mode 100644 index 000000000000..264724cca11b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Network Management 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 Network Management 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-network-management/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py b/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py new file mode 100644 index 000000000000..a303b54b23a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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-network-management documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-network-management" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-network-management-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-network-management.tex", + u"google-cloud-network-management Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-network-management", + u"Google Cloud Network Management 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-network-management", + u"google-cloud-network-management Documentation", + author, + "google-cloud-network-management", + "GAPIC library for Google Cloud Network Management 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-network-management/v1/docs/index.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/index.rst new file mode 100644 index 000000000000..df608d7805a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + network_management_v1/services_ + network_management_v1/types_ diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst new file mode 100644 index 000000000000..1d3502a632c9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst @@ -0,0 +1,10 @@ +ReachabilityService +------------------------------------- + +.. automodule:: google.cloud.network_management_v1.services.reachability_service + :members: + :inherited-members: + +.. automodule:: google.cloud.network_management_v1.services.reachability_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst new file mode 100644 index 000000000000..e26ca50e5fc4 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Network Management v1 API +=================================================== +.. toctree:: + :maxdepth: 2 + + reachability_service diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst new file mode 100644 index 000000000000..11bcca7b4b58 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Network Management v1 API +================================================ + +.. automodule:: google.cloud.network_management_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py new file mode 100644 index 000000000000..23a237dd11fa --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py @@ -0,0 +1,117 @@ +# -*- 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.network_management import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.network_management_v1.services.reachability_service.client import ReachabilityServiceClient +from google.cloud.network_management_v1.services.reachability_service.async_client import ReachabilityServiceAsyncClient + +from google.cloud.network_management_v1.types.connectivity_test import ConnectivityTest +from google.cloud.network_management_v1.types.connectivity_test import Endpoint +from google.cloud.network_management_v1.types.connectivity_test import LatencyDistribution +from google.cloud.network_management_v1.types.connectivity_test import LatencyPercentile +from google.cloud.network_management_v1.types.connectivity_test import ProbingDetails +from google.cloud.network_management_v1.types.connectivity_test import ReachabilityDetails +from google.cloud.network_management_v1.types.reachability import CreateConnectivityTestRequest +from google.cloud.network_management_v1.types.reachability import DeleteConnectivityTestRequest +from google.cloud.network_management_v1.types.reachability import GetConnectivityTestRequest +from google.cloud.network_management_v1.types.reachability import ListConnectivityTestsRequest +from google.cloud.network_management_v1.types.reachability import ListConnectivityTestsResponse +from google.cloud.network_management_v1.types.reachability import OperationMetadata +from google.cloud.network_management_v1.types.reachability import RerunConnectivityTestRequest +from google.cloud.network_management_v1.types.reachability import UpdateConnectivityTestRequest +from google.cloud.network_management_v1.types.trace import AbortInfo +from google.cloud.network_management_v1.types.trace import AppEngineVersionInfo +from google.cloud.network_management_v1.types.trace import CloudFunctionInfo +from google.cloud.network_management_v1.types.trace import CloudRunRevisionInfo +from google.cloud.network_management_v1.types.trace import CloudSQLInstanceInfo +from google.cloud.network_management_v1.types.trace import DeliverInfo +from google.cloud.network_management_v1.types.trace import DropInfo +from google.cloud.network_management_v1.types.trace import EndpointInfo +from google.cloud.network_management_v1.types.trace import FirewallInfo +from google.cloud.network_management_v1.types.trace import ForwardInfo +from google.cloud.network_management_v1.types.trace import ForwardingRuleInfo +from google.cloud.network_management_v1.types.trace import GKEMasterInfo +from google.cloud.network_management_v1.types.trace import GoogleServiceInfo +from google.cloud.network_management_v1.types.trace import InstanceInfo +from google.cloud.network_management_v1.types.trace import LoadBalancerBackend +from google.cloud.network_management_v1.types.trace import LoadBalancerBackendInfo +from google.cloud.network_management_v1.types.trace import LoadBalancerInfo +from google.cloud.network_management_v1.types.trace import NatInfo +from google.cloud.network_management_v1.types.trace import NetworkInfo +from google.cloud.network_management_v1.types.trace import ProxyConnectionInfo +from google.cloud.network_management_v1.types.trace import RedisClusterInfo +from google.cloud.network_management_v1.types.trace import RedisInstanceInfo +from google.cloud.network_management_v1.types.trace import RouteInfo +from google.cloud.network_management_v1.types.trace import ServerlessNegInfo +from google.cloud.network_management_v1.types.trace import Step +from google.cloud.network_management_v1.types.trace import StorageBucketInfo +from google.cloud.network_management_v1.types.trace import Trace +from google.cloud.network_management_v1.types.trace import VpcConnectorInfo +from google.cloud.network_management_v1.types.trace import VpnGatewayInfo +from google.cloud.network_management_v1.types.trace import VpnTunnelInfo +from google.cloud.network_management_v1.types.trace import LoadBalancerType + +__all__ = ('ReachabilityServiceClient', + 'ReachabilityServiceAsyncClient', + 'ConnectivityTest', + 'Endpoint', + 'LatencyDistribution', + 'LatencyPercentile', + 'ProbingDetails', + 'ReachabilityDetails', + 'CreateConnectivityTestRequest', + 'DeleteConnectivityTestRequest', + 'GetConnectivityTestRequest', + 'ListConnectivityTestsRequest', + 'ListConnectivityTestsResponse', + 'OperationMetadata', + 'RerunConnectivityTestRequest', + 'UpdateConnectivityTestRequest', + 'AbortInfo', + 'AppEngineVersionInfo', + 'CloudFunctionInfo', + 'CloudRunRevisionInfo', + 'CloudSQLInstanceInfo', + 'DeliverInfo', + 'DropInfo', + 'EndpointInfo', + 'FirewallInfo', + 'ForwardInfo', + 'ForwardingRuleInfo', + 'GKEMasterInfo', + 'GoogleServiceInfo', + 'InstanceInfo', + 'LoadBalancerBackend', + 'LoadBalancerBackendInfo', + 'LoadBalancerInfo', + 'NatInfo', + 'NetworkInfo', + 'ProxyConnectionInfo', + 'RedisClusterInfo', + 'RedisInstanceInfo', + 'RouteInfo', + 'ServerlessNegInfo', + 'Step', + 'StorageBucketInfo', + 'Trace', + 'VpcConnectorInfo', + 'VpnGatewayInfo', + 'VpnTunnelInfo', + 'LoadBalancerType', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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-network-management/v1/google/cloud/network_management/py.typed b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed new file mode 100644 index 000000000000..5aa063ef7ba9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-management package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py new file mode 100644 index 000000000000..a55edfec563a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py @@ -0,0 +1,118 @@ +# -*- 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.network_management_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.reachability_service import ReachabilityServiceClient +from .services.reachability_service import ReachabilityServiceAsyncClient + +from .types.connectivity_test import ConnectivityTest +from .types.connectivity_test import Endpoint +from .types.connectivity_test import LatencyDistribution +from .types.connectivity_test import LatencyPercentile +from .types.connectivity_test import ProbingDetails +from .types.connectivity_test import ReachabilityDetails +from .types.reachability import CreateConnectivityTestRequest +from .types.reachability import DeleteConnectivityTestRequest +from .types.reachability import GetConnectivityTestRequest +from .types.reachability import ListConnectivityTestsRequest +from .types.reachability import ListConnectivityTestsResponse +from .types.reachability import OperationMetadata +from .types.reachability import RerunConnectivityTestRequest +from .types.reachability import UpdateConnectivityTestRequest +from .types.trace import AbortInfo +from .types.trace import AppEngineVersionInfo +from .types.trace import CloudFunctionInfo +from .types.trace import CloudRunRevisionInfo +from .types.trace import CloudSQLInstanceInfo +from .types.trace import DeliverInfo +from .types.trace import DropInfo +from .types.trace import EndpointInfo +from .types.trace import FirewallInfo +from .types.trace import ForwardInfo +from .types.trace import ForwardingRuleInfo +from .types.trace import GKEMasterInfo +from .types.trace import GoogleServiceInfo +from .types.trace import InstanceInfo +from .types.trace import LoadBalancerBackend +from .types.trace import LoadBalancerBackendInfo +from .types.trace import LoadBalancerInfo +from .types.trace import NatInfo +from .types.trace import NetworkInfo +from .types.trace import ProxyConnectionInfo +from .types.trace import RedisClusterInfo +from .types.trace import RedisInstanceInfo +from .types.trace import RouteInfo +from .types.trace import ServerlessNegInfo +from .types.trace import Step +from .types.trace import StorageBucketInfo +from .types.trace import Trace +from .types.trace import VpcConnectorInfo +from .types.trace import VpnGatewayInfo +from .types.trace import VpnTunnelInfo +from .types.trace import LoadBalancerType + +__all__ = ( + 'ReachabilityServiceAsyncClient', +'AbortInfo', +'AppEngineVersionInfo', +'CloudFunctionInfo', +'CloudRunRevisionInfo', +'CloudSQLInstanceInfo', +'ConnectivityTest', +'CreateConnectivityTestRequest', +'DeleteConnectivityTestRequest', +'DeliverInfo', +'DropInfo', +'Endpoint', +'EndpointInfo', +'FirewallInfo', +'ForwardInfo', +'ForwardingRuleInfo', +'GKEMasterInfo', +'GetConnectivityTestRequest', +'GoogleServiceInfo', +'InstanceInfo', +'LatencyDistribution', +'LatencyPercentile', +'ListConnectivityTestsRequest', +'ListConnectivityTestsResponse', +'LoadBalancerBackend', +'LoadBalancerBackendInfo', +'LoadBalancerInfo', +'LoadBalancerType', +'NatInfo', +'NetworkInfo', +'OperationMetadata', +'ProbingDetails', +'ProxyConnectionInfo', +'ReachabilityDetails', +'ReachabilityServiceClient', +'RedisClusterInfo', +'RedisInstanceInfo', +'RerunConnectivityTestRequest', +'RouteInfo', +'ServerlessNegInfo', +'Step', +'StorageBucketInfo', +'Trace', +'UpdateConnectivityTestRequest', +'VpcConnectorInfo', +'VpnGatewayInfo', +'VpnTunnelInfo', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json new file mode 100644 index 000000000000..6c5315440fef --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json @@ -0,0 +1,118 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.network_management_v1", + "protoPackage": "google.cloud.networkmanagement.v1", + "schema": "1.0", + "services": { + "ReachabilityService": { + "clients": { + "grpc": { + "libraryClient": "ReachabilityServiceClient", + "rpcs": { + "CreateConnectivityTest": { + "methods": [ + "create_connectivity_test" + ] + }, + "DeleteConnectivityTest": { + "methods": [ + "delete_connectivity_test" + ] + }, + "GetConnectivityTest": { + "methods": [ + "get_connectivity_test" + ] + }, + "ListConnectivityTests": { + "methods": [ + "list_connectivity_tests" + ] + }, + "RerunConnectivityTest": { + "methods": [ + "rerun_connectivity_test" + ] + }, + "UpdateConnectivityTest": { + "methods": [ + "update_connectivity_test" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ReachabilityServiceAsyncClient", + "rpcs": { + "CreateConnectivityTest": { + "methods": [ + "create_connectivity_test" + ] + }, + "DeleteConnectivityTest": { + "methods": [ + "delete_connectivity_test" + ] + }, + "GetConnectivityTest": { + "methods": [ + "get_connectivity_test" + ] + }, + "ListConnectivityTests": { + "methods": [ + "list_connectivity_tests" + ] + }, + "RerunConnectivityTest": { + "methods": [ + "rerun_connectivity_test" + ] + }, + "UpdateConnectivityTest": { + "methods": [ + "update_connectivity_test" + ] + } + } + }, + "rest": { + "libraryClient": "ReachabilityServiceClient", + "rpcs": { + "CreateConnectivityTest": { + "methods": [ + "create_connectivity_test" + ] + }, + "DeleteConnectivityTest": { + "methods": [ + "delete_connectivity_test" + ] + }, + "GetConnectivityTest": { + "methods": [ + "get_connectivity_test" + ] + }, + "ListConnectivityTests": { + "methods": [ + "list_connectivity_tests" + ] + }, + "RerunConnectivityTest": { + "methods": [ + "rerun_connectivity_test" + ] + }, + "UpdateConnectivityTest": { + "methods": [ + "update_connectivity_test" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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-network-management/v1/google/cloud/network_management_v1/py.typed b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed new file mode 100644 index 000000000000..5aa063ef7ba9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-management package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py new file mode 100644 index 000000000000..6f536eeb4ca5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 ReachabilityServiceClient +from .async_client import ReachabilityServiceAsyncClient + +__all__ = ( + 'ReachabilityServiceClient', + 'ReachabilityServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py new file mode 100644 index 000000000000..0ae89e6c03d8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py @@ -0,0 +1,1597 @@ +# -*- 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.network_management_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.location import locations_pb2 # type: ignore +from google.cloud.network_management_v1.services.reachability_service import pagers +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport +from .client import ReachabilityServiceClient + + +class ReachabilityServiceAsyncClient: + """The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + """ + + _client: ReachabilityServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ReachabilityServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ReachabilityServiceClient._DEFAULT_UNIVERSE + + connectivity_test_path = staticmethod(ReachabilityServiceClient.connectivity_test_path) + parse_connectivity_test_path = staticmethod(ReachabilityServiceClient.parse_connectivity_test_path) + common_billing_account_path = staticmethod(ReachabilityServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ReachabilityServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ReachabilityServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ReachabilityServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ReachabilityServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ReachabilityServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ReachabilityServiceClient.common_project_path) + parse_common_project_path = staticmethod(ReachabilityServiceClient.parse_common_project_path) + common_location_path = staticmethod(ReachabilityServiceClient.common_location_path) + parse_common_location_path = staticmethod(ReachabilityServiceClient.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: + ReachabilityServiceAsyncClient: The constructed client. + """ + return ReachabilityServiceClient.from_service_account_info.__func__(ReachabilityServiceAsyncClient, 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: + ReachabilityServiceAsyncClient: The constructed client. + """ + return ReachabilityServiceClient.from_service_account_file.__func__(ReachabilityServiceAsyncClient, 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 ReachabilityServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ReachabilityServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ReachabilityServiceTransport: 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 = ReachabilityServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ReachabilityServiceTransport, Callable[..., ReachabilityServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the reachability service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ReachabilityServiceTransport,Callable[..., ReachabilityServiceTransport]]]): + 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 ReachabilityServiceTransport 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 = ReachabilityServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_connectivity_tests(self, + request: Optional[Union[reachability.ListConnectivityTestsRequest, 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.ListConnectivityTestsAsyncPager: + r"""Lists all Connectivity Tests owned by a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_list_connectivity_tests(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.ListConnectivityTestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_connectivity_tests(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.ListConnectivityTestsRequest, dict]]): + The request object. Request for the ``ListConnectivityTests`` method. + parent (:class:`str`): + Required. The parent resource of the Connectivity Tests: + ``projects/{project_id}/locations/global`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsAsyncPager: + Response for the ListConnectivityTests method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, reachability.ListConnectivityTestsRequest): + request = reachability.ListConnectivityTestsRequest(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_connectivity_tests] + + # 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.ListConnectivityTestsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_connectivity_test(self, + request: Optional[Union[reachability.GetConnectivityTestRequest, 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]] = (), + ) -> connectivity_test.ConnectivityTest: + r"""Gets the details of a specific Connectivity Test. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_get_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.GetConnectivityTestRequest( + name="name_value", + ) + + # Make the request + response = await client.get_connectivity_test(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.GetConnectivityTestRequest, dict]]): + The request object. Request for the ``GetConnectivityTest`` method. + name (:class:`str`): + Required. ``ConnectivityTest`` resource name using the + form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + + 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.network_management_v1.types.ConnectivityTest: + A Connectivity Test for a network + reachability analysis. + + """ + # Create or coerce a 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, reachability.GetConnectivityTestRequest): + request = reachability.GetConnectivityTestRequest(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_connectivity_test] + + # 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_connectivity_test(self, + request: Optional[Union[reachability.CreateConnectivityTestRequest, dict]] = None, + *, + parent: Optional[str] = None, + test_id: Optional[str] = None, + resource: Optional[connectivity_test.ConnectivityTest] = 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 Connectivity Test. After you create a test, the + reachability analysis is performed as part of the long running + operation, which completes when the analysis completes. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, containing non-existent resources in the + network, or you don't have read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + AMBIGUOUS. For more information, see the Connectivity Test + documentation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_create_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.CreateConnectivityTestRequest( + parent="parent_value", + test_id="test_id_value", + ) + + # Make the request + operation = client.create_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.CreateConnectivityTestRequest, dict]]): + The request object. Request for the ``CreateConnectivityTest`` method. + parent (:class:`str`): + Required. The parent resource of the Connectivity Test + to create: ``projects/{project_id}/locations/global`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_id (:class:`str`): + Required. The logical name of the Connectivity Test in + your project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-40 characters. + - Must end with a number or a letter. + - Must be unique within the customer project + + This corresponds to the ``test_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (:class:`google.cloud.network_management_v1.types.ConnectivityTest`): + Required. A ``ConnectivityTest`` resource + This corresponds to the ``resource`` 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.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a 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, test_id, resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.CreateConnectivityTestRequest): + request = reachability.CreateConnectivityTestRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if test_id is not None: + request.test_id = test_id + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_connectivity_test] + + # 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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_connectivity_test(self, + request: Optional[Union[reachability.UpdateConnectivityTestRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + resource: Optional[connectivity_test.ConnectivityTest] = 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 configuration of an existing ``ConnectivityTest``. + After you update a test, the reachability analysis is performed + as part of the long running operation, which completes when the + analysis completes. The Reachability state in the test resource + is updated with the new result. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, they contain non-existent resources in the + network, or the user does not have read permissions to the + network configurations of listed projects), then the + reachability result returns a value of UNKNOWN. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for + more details. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_update_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.UpdateConnectivityTestRequest( + ) + + # Make the request + operation = client.update_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.UpdateConnectivityTestRequest, dict]]): + The request object. Request for the ``UpdateConnectivityTest`` method. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask of fields to update. + At least one path must be supplied in + this field. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (:class:`google.cloud.network_management_v1.types.ConnectivityTest`): + Required. Only fields specified in update_mask are + updated. + + This corresponds to the ``resource`` 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.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a 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([update_mask, resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.UpdateConnectivityTestRequest): + request = reachability.UpdateConnectivityTestRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if update_mask is not None: + request.update_mask = update_mask + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_connectivity_test] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource.name", request.resource.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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + async def rerun_connectivity_test(self, + request: Optional[Union[reachability.RerunConnectivityTestRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Rerun an existing ``ConnectivityTest``. After the user triggers + the rerun, the reachability analysis is performed as part of the + long running operation, which completes when the analysis + completes. + + Even though the test configuration remains the same, the + reachability result may change due to underlying network + configuration changes. + + If the endpoint specifications in ``ConnectivityTest`` become + invalid (for example, specified resources are deleted in the + network, or you lost read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_rerun_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.RerunConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.rerun_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.RerunConnectivityTestRequest, dict]]): + The request object. Request for the ``RerunConnectivityTest`` 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: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.RerunConnectivityTestRequest): + request = reachability.RerunConnectivityTestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.rerun_connectivity_test] + + # 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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_connectivity_test(self, + request: Optional[Union[reachability.DeleteConnectivityTestRequest, 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 specific ``ConnectivityTest``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_delete_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.DeleteConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.DeleteConnectivityTestRequest, dict]]): + The request object. Request for the ``DeleteConnectivityTest`` method. + name (:class:`str`): + Required. Connectivity Test resource name using the + form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + + 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, reachability.DeleteConnectivityTestRequest): + request = reachability.DeleteConnectivityTestRequest(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_connectivity_test] + + # 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=reachability.OperationMetadata, + ) + + # 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, 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) -> "ReachabilityServiceAsyncClient": + 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__ = ( + "ReachabilityServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py new file mode 100644 index 000000000000..af1f94e73757 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py @@ -0,0 +1,1917 @@ +# -*- 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.network_management_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.location import locations_pb2 # type: ignore +from google.cloud.network_management_v1.services.reachability_service import pagers +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ReachabilityServiceGrpcTransport +from .transports.grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport +from .transports.rest import ReachabilityServiceRestTransport + + +class ReachabilityServiceClientMeta(type): + """Metaclass for the ReachabilityService 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[ReachabilityServiceTransport]] + _transport_registry["grpc"] = ReachabilityServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ReachabilityServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ReachabilityServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ReachabilityServiceTransport]: + """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 ReachabilityServiceClient(metaclass=ReachabilityServiceClientMeta): + """The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + """ + + @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 = "networkmanagement.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networkmanagement.{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: + ReachabilityServiceClient: 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: + ReachabilityServiceClient: 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) -> ReachabilityServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ReachabilityServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def connectivity_test_path(project: str,test: str,) -> str: + """Returns a fully-qualified connectivity_test string.""" + return "projects/{project}/locations/global/connectivityTests/{test}".format(project=project, test=test, ) + + @staticmethod + def parse_connectivity_test_path(path: str) -> Dict[str,str]: + """Parses a connectivity_test path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/global/connectivityTests/(?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 = ReachabilityServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ReachabilityServiceClient._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 = ReachabilityServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ReachabilityServiceTransport, Callable[..., ReachabilityServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the reachability service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ReachabilityServiceTransport,Callable[..., ReachabilityServiceTransport]]]): + 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 ReachabilityServiceTransport 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 = ReachabilityServiceClient._read_environment_variables() + self._client_cert_source = ReachabilityServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ReachabilityServiceClient._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, ReachabilityServiceTransport) + if transport_provided: + # transport is a ReachabilityServiceTransport 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(ReachabilityServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ReachabilityServiceClient._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[ReachabilityServiceTransport], Callable[..., ReachabilityServiceTransport]] = ( + ReachabilityServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ReachabilityServiceTransport], 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_connectivity_tests(self, + request: Optional[Union[reachability.ListConnectivityTestsRequest, 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.ListConnectivityTestsPager: + r"""Lists all Connectivity Tests owned by a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_list_connectivity_tests(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.ListConnectivityTestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_connectivity_tests(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.ListConnectivityTestsRequest, dict]): + The request object. Request for the ``ListConnectivityTests`` method. + parent (str): + Required. The parent resource of the Connectivity Tests: + ``projects/{project_id}/locations/global`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsPager: + Response for the ListConnectivityTests method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, reachability.ListConnectivityTestsRequest): + request = reachability.ListConnectivityTestsRequest(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_connectivity_tests] + + # 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.ListConnectivityTestsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_connectivity_test(self, + request: Optional[Union[reachability.GetConnectivityTestRequest, 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]] = (), + ) -> connectivity_test.ConnectivityTest: + r"""Gets the details of a specific Connectivity Test. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_get_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.GetConnectivityTestRequest( + name="name_value", + ) + + # Make the request + response = client.get_connectivity_test(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.GetConnectivityTestRequest, dict]): + The request object. Request for the ``GetConnectivityTest`` method. + name (str): + Required. ``ConnectivityTest`` resource name using the + form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + + 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.network_management_v1.types.ConnectivityTest: + A Connectivity Test for a network + reachability analysis. + + """ + # Create or coerce a 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, reachability.GetConnectivityTestRequest): + request = reachability.GetConnectivityTestRequest(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_connectivity_test] + + # 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_connectivity_test(self, + request: Optional[Union[reachability.CreateConnectivityTestRequest, dict]] = None, + *, + parent: Optional[str] = None, + test_id: Optional[str] = None, + resource: Optional[connectivity_test.ConnectivityTest] = 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 Connectivity Test. After you create a test, the + reachability analysis is performed as part of the long running + operation, which completes when the analysis completes. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, containing non-existent resources in the + network, or you don't have read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + AMBIGUOUS. For more information, see the Connectivity Test + documentation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_create_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.CreateConnectivityTestRequest( + parent="parent_value", + test_id="test_id_value", + ) + + # Make the request + operation = client.create_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.CreateConnectivityTestRequest, dict]): + The request object. Request for the ``CreateConnectivityTest`` method. + parent (str): + Required. The parent resource of the Connectivity Test + to create: ``projects/{project_id}/locations/global`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_id (str): + Required. The logical name of the Connectivity Test in + your project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-40 characters. + - Must end with a number or a letter. + - Must be unique within the customer project + + This corresponds to the ``test_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (google.cloud.network_management_v1.types.ConnectivityTest): + Required. A ``ConnectivityTest`` resource + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a 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, test_id, resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.CreateConnectivityTestRequest): + request = reachability.CreateConnectivityTestRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if test_id is not None: + request.test_id = test_id + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_connectivity_test] + + # 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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_connectivity_test(self, + request: Optional[Union[reachability.UpdateConnectivityTestRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + resource: Optional[connectivity_test.ConnectivityTest] = 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 configuration of an existing ``ConnectivityTest``. + After you update a test, the reachability analysis is performed + as part of the long running operation, which completes when the + analysis completes. The Reachability state in the test resource + is updated with the new result. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, they contain non-existent resources in the + network, or the user does not have read permissions to the + network configurations of listed projects), then the + reachability result returns a value of UNKNOWN. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for + more details. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_update_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.UpdateConnectivityTestRequest( + ) + + # Make the request + operation = client.update_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.UpdateConnectivityTestRequest, dict]): + The request object. Request for the ``UpdateConnectivityTest`` method. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. + At least one path must be supplied in + this field. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (google.cloud.network_management_v1.types.ConnectivityTest): + Required. Only fields specified in update_mask are + updated. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a 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([update_mask, resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.UpdateConnectivityTestRequest): + request = reachability.UpdateConnectivityTestRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if update_mask is not None: + request.update_mask = update_mask + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_connectivity_test] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource.name", request.resource.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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + def rerun_connectivity_test(self, + request: Optional[Union[reachability.RerunConnectivityTestRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Rerun an existing ``ConnectivityTest``. After the user triggers + the rerun, the reachability analysis is performed as part of the + long running operation, which completes when the analysis + completes. + + Even though the test configuration remains the same, the + reachability result may change due to underlying network + configuration changes. + + If the endpoint specifications in ``ConnectivityTest`` become + invalid (for example, specified resources are deleted in the + network, or you lost read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_rerun_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.RerunConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.rerun_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.RerunConnectivityTestRequest, dict]): + The request object. Request for the ``RerunConnectivityTest`` 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: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.RerunConnectivityTestRequest): + request = reachability.RerunConnectivityTestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rerun_connectivity_test] + + # 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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_connectivity_test(self, + request: Optional[Union[reachability.DeleteConnectivityTestRequest, 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 specific ``ConnectivityTest``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_delete_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.DeleteConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.DeleteConnectivityTestRequest, dict]): + The request object. Request for the ``DeleteConnectivityTest`` method. + name (str): + Required. Connectivity Test resource name using the + form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + + 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, reachability.DeleteConnectivityTestRequest): + request = reachability.DeleteConnectivityTestRequest(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_connectivity_test] + + # 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=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ReachabilityServiceClient": + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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__ = ( + "ReachabilityServiceClient", +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py new file mode 100644 index 000000000000..99e5a56eabf4 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py @@ -0,0 +1,163 @@ +# -*- 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.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability + + +class ListConnectivityTestsPager: + """A pager for iterating through ``list_connectivity_tests`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConnectivityTests`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` + 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[..., reachability.ListConnectivityTestsResponse], + request: reachability.ListConnectivityTestsRequest, + response: reachability.ListConnectivityTestsResponse, + *, + 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.network_management_v1.types.ListConnectivityTestsRequest): + The initial request object. + response (google.cloud.network_management_v1.types.ListConnectivityTestsResponse): + 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 = reachability.ListConnectivityTestsRequest(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[reachability.ListConnectivityTestsResponse]: + 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[connectivity_test.ConnectivityTest]: + for page in self.pages: + yield from page.resources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConnectivityTestsAsyncPager: + """A pager for iterating through ``list_connectivity_tests`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConnectivityTests`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` + 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[reachability.ListConnectivityTestsResponse]], + request: reachability.ListConnectivityTestsRequest, + response: reachability.ListConnectivityTestsResponse, + *, + 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.network_management_v1.types.ListConnectivityTestsRequest): + The initial request object. + response (google.cloud.network_management_v1.types.ListConnectivityTestsResponse): + 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 = reachability.ListConnectivityTestsRequest(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[reachability.ListConnectivityTestsResponse]: + 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[connectivity_test.ConnectivityTest]: + async def async_generator(): + async for page in self.pages: + for response in page.resources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst new file mode 100644 index 000000000000..b6e73840492e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ReachabilityServiceTransport` is the ABC for all transports. +- public child `ReachabilityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ReachabilityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseReachabilityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ReachabilityServiceRestTransport` 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-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py new file mode 100644 index 000000000000..e03fcb9eb663 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- 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 ReachabilityServiceTransport +from .grpc import ReachabilityServiceGrpcTransport +from .grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport +from .rest import ReachabilityServiceRestTransport +from .rest import ReachabilityServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ReachabilityServiceTransport]] +_transport_registry['grpc'] = ReachabilityServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ReachabilityServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ReachabilityServiceRestTransport + +__all__ = ( + 'ReachabilityServiceTransport', + 'ReachabilityServiceGrpcTransport', + 'ReachabilityServiceGrpcAsyncIOTransport', + 'ReachabilityServiceRestTransport', + 'ReachabilityServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py new file mode 100644 index 000000000000..3d64ec294ab6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py @@ -0,0 +1,362 @@ +# -*- 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.network_management_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.location import locations_pb2 # type: ignore +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ReachabilityServiceTransport(abc.ABC): + """Abstract transport class for ReachabilityService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'networkmanagement.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: 'networkmanagement.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_connectivity_tests: gapic_v1.method.wrap_method( + self.list_connectivity_tests, + default_timeout=None, + client_info=client_info, + ), + self.get_connectivity_test: gapic_v1.method.wrap_method( + self.get_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.create_connectivity_test: gapic_v1.method.wrap_method( + self.create_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.update_connectivity_test: gapic_v1.method.wrap_method( + self.update_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.rerun_connectivity_test: gapic_v1.method.wrap_method( + self.rerun_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.delete_connectivity_test: gapic_v1.method.wrap_method( + self.delete_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_connectivity_tests(self) -> Callable[ + [reachability.ListConnectivityTestsRequest], + Union[ + reachability.ListConnectivityTestsResponse, + Awaitable[reachability.ListConnectivityTestsResponse] + ]]: + raise NotImplementedError() + + @property + def get_connectivity_test(self) -> Callable[ + [reachability.GetConnectivityTestRequest], + Union[ + connectivity_test.ConnectivityTest, + Awaitable[connectivity_test.ConnectivityTest] + ]]: + raise NotImplementedError() + + @property + def create_connectivity_test(self) -> Callable[ + [reachability.CreateConnectivityTestRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_connectivity_test(self) -> Callable[ + [reachability.UpdateConnectivityTestRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rerun_connectivity_test(self) -> Callable[ + [reachability.RerunConnectivityTestRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_connectivity_test(self) -> Callable[ + [reachability.DeleteConnectivityTestRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ReachabilityServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py new file mode 100644 index 000000000000..04909d6e22c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py @@ -0,0 +1,660 @@ +# -*- 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.location import locations_pb2 # type: ignore +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO + + +class ReachabilityServiceGrpcTransport(ReachabilityServiceTransport): + """gRPC backend transport for ReachabilityService. + + The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + + 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 = 'networkmanagement.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: 'networkmanagement.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 = 'networkmanagement.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_connectivity_tests(self) -> Callable[ + [reachability.ListConnectivityTestsRequest], + reachability.ListConnectivityTestsResponse]: + r"""Return a callable for the list connectivity tests method over gRPC. + + Lists all Connectivity Tests owned by a project. + + Returns: + Callable[[~.ListConnectivityTestsRequest], + ~.ListConnectivityTestsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connectivity_tests' not in self._stubs: + self._stubs['list_connectivity_tests'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/ListConnectivityTests', + request_serializer=reachability.ListConnectivityTestsRequest.serialize, + response_deserializer=reachability.ListConnectivityTestsResponse.deserialize, + ) + return self._stubs['list_connectivity_tests'] + + @property + def get_connectivity_test(self) -> Callable[ + [reachability.GetConnectivityTestRequest], + connectivity_test.ConnectivityTest]: + r"""Return a callable for the get connectivity test method over gRPC. + + Gets the details of a specific Connectivity Test. + + Returns: + Callable[[~.GetConnectivityTestRequest], + ~.ConnectivityTest]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connectivity_test' not in self._stubs: + self._stubs['get_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/GetConnectivityTest', + request_serializer=reachability.GetConnectivityTestRequest.serialize, + response_deserializer=connectivity_test.ConnectivityTest.deserialize, + ) + return self._stubs['get_connectivity_test'] + + @property + def create_connectivity_test(self) -> Callable[ + [reachability.CreateConnectivityTestRequest], + operations_pb2.Operation]: + r"""Return a callable for the create connectivity test method over gRPC. + + Creates a new Connectivity Test. After you create a test, the + reachability analysis is performed as part of the long running + operation, which completes when the analysis completes. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, containing non-existent resources in the + network, or you don't have read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + AMBIGUOUS. For more information, see the Connectivity Test + documentation. + + Returns: + Callable[[~.CreateConnectivityTestRequest], + ~.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_connectivity_test' not in self._stubs: + self._stubs['create_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/CreateConnectivityTest', + request_serializer=reachability.CreateConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_connectivity_test'] + + @property + def update_connectivity_test(self) -> Callable[ + [reachability.UpdateConnectivityTestRequest], + operations_pb2.Operation]: + r"""Return a callable for the update connectivity test method over gRPC. + + Updates the configuration of an existing ``ConnectivityTest``. + After you update a test, the reachability analysis is performed + as part of the long running operation, which completes when the + analysis completes. The Reachability state in the test resource + is updated with the new result. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, they contain non-existent resources in the + network, or the user does not have read permissions to the + network configurations of listed projects), then the + reachability result returns a value of UNKNOWN. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for + more details. + + Returns: + Callable[[~.UpdateConnectivityTestRequest], + ~.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_connectivity_test' not in self._stubs: + self._stubs['update_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/UpdateConnectivityTest', + request_serializer=reachability.UpdateConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_connectivity_test'] + + @property + def rerun_connectivity_test(self) -> Callable[ + [reachability.RerunConnectivityTestRequest], + operations_pb2.Operation]: + r"""Return a callable for the rerun connectivity test method over gRPC. + + Rerun an existing ``ConnectivityTest``. After the user triggers + the rerun, the reachability analysis is performed as part of the + long running operation, which completes when the analysis + completes. + + Even though the test configuration remains the same, the + reachability result may change due to underlying network + configuration changes. + + If the endpoint specifications in ``ConnectivityTest`` become + invalid (for example, specified resources are deleted in the + network, or you lost read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + Returns: + Callable[[~.RerunConnectivityTestRequest], + ~.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 'rerun_connectivity_test' not in self._stubs: + self._stubs['rerun_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/RerunConnectivityTest', + request_serializer=reachability.RerunConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rerun_connectivity_test'] + + @property + def delete_connectivity_test(self) -> Callable[ + [reachability.DeleteConnectivityTestRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete connectivity test method over gRPC. + + Deletes a specific ``ConnectivityTest``. + + Returns: + Callable[[~.DeleteConnectivityTestRequest], + ~.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_connectivity_test' not in self._stubs: + self._stubs['delete_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/DeleteConnectivityTest', + request_serializer=reachability.DeleteConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_connectivity_test'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ReachabilityServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..15d349b57214 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py @@ -0,0 +1,751 @@ +# -*- 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.location import locations_pb2 # type: ignore +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ReachabilityServiceGrpcTransport + + +class ReachabilityServiceGrpcAsyncIOTransport(ReachabilityServiceTransport): + """gRPC AsyncIO backend transport for ReachabilityService. + + The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + + 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 = 'networkmanagement.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 = 'networkmanagement.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: 'networkmanagement.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_connectivity_tests(self) -> Callable[ + [reachability.ListConnectivityTestsRequest], + Awaitable[reachability.ListConnectivityTestsResponse]]: + r"""Return a callable for the list connectivity tests method over gRPC. + + Lists all Connectivity Tests owned by a project. + + Returns: + Callable[[~.ListConnectivityTestsRequest], + Awaitable[~.ListConnectivityTestsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connectivity_tests' not in self._stubs: + self._stubs['list_connectivity_tests'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/ListConnectivityTests', + request_serializer=reachability.ListConnectivityTestsRequest.serialize, + response_deserializer=reachability.ListConnectivityTestsResponse.deserialize, + ) + return self._stubs['list_connectivity_tests'] + + @property + def get_connectivity_test(self) -> Callable[ + [reachability.GetConnectivityTestRequest], + Awaitable[connectivity_test.ConnectivityTest]]: + r"""Return a callable for the get connectivity test method over gRPC. + + Gets the details of a specific Connectivity Test. + + Returns: + Callable[[~.GetConnectivityTestRequest], + Awaitable[~.ConnectivityTest]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connectivity_test' not in self._stubs: + self._stubs['get_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/GetConnectivityTest', + request_serializer=reachability.GetConnectivityTestRequest.serialize, + response_deserializer=connectivity_test.ConnectivityTest.deserialize, + ) + return self._stubs['get_connectivity_test'] + + @property + def create_connectivity_test(self) -> Callable[ + [reachability.CreateConnectivityTestRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create connectivity test method over gRPC. + + Creates a new Connectivity Test. After you create a test, the + reachability analysis is performed as part of the long running + operation, which completes when the analysis completes. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, containing non-existent resources in the + network, or you don't have read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + AMBIGUOUS. For more information, see the Connectivity Test + documentation. + + Returns: + Callable[[~.CreateConnectivityTestRequest], + 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_connectivity_test' not in self._stubs: + self._stubs['create_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/CreateConnectivityTest', + request_serializer=reachability.CreateConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_connectivity_test'] + + @property + def update_connectivity_test(self) -> Callable[ + [reachability.UpdateConnectivityTestRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update connectivity test method over gRPC. + + Updates the configuration of an existing ``ConnectivityTest``. + After you update a test, the reachability analysis is performed + as part of the long running operation, which completes when the + analysis completes. The Reachability state in the test resource + is updated with the new result. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, they contain non-existent resources in the + network, or the user does not have read permissions to the + network configurations of listed projects), then the + reachability result returns a value of UNKNOWN. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for + more details. + + Returns: + Callable[[~.UpdateConnectivityTestRequest], + 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_connectivity_test' not in self._stubs: + self._stubs['update_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/UpdateConnectivityTest', + request_serializer=reachability.UpdateConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_connectivity_test'] + + @property + def rerun_connectivity_test(self) -> Callable[ + [reachability.RerunConnectivityTestRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rerun connectivity test method over gRPC. + + Rerun an existing ``ConnectivityTest``. After the user triggers + the rerun, the reachability analysis is performed as part of the + long running operation, which completes when the analysis + completes. + + Even though the test configuration remains the same, the + reachability result may change due to underlying network + configuration changes. + + If the endpoint specifications in ``ConnectivityTest`` become + invalid (for example, specified resources are deleted in the + network, or you lost read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + Returns: + Callable[[~.RerunConnectivityTestRequest], + 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 'rerun_connectivity_test' not in self._stubs: + self._stubs['rerun_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/RerunConnectivityTest', + request_serializer=reachability.RerunConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rerun_connectivity_test'] + + @property + def delete_connectivity_test(self) -> Callable[ + [reachability.DeleteConnectivityTestRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete connectivity test method over gRPC. + + Deletes a specific ``ConnectivityTest``. + + Returns: + Callable[[~.DeleteConnectivityTestRequest], + 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_connectivity_test' not in self._stubs: + self._stubs['delete_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/DeleteConnectivityTest', + request_serializer=reachability.DeleteConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_connectivity_test'] + + 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_connectivity_tests: self._wrap_method( + self.list_connectivity_tests, + default_timeout=None, + client_info=client_info, + ), + self.get_connectivity_test: self._wrap_method( + self.get_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.create_connectivity_test: self._wrap_method( + self.create_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.update_connectivity_test: self._wrap_method( + self.update_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.rerun_connectivity_test: self._wrap_method( + self.rerun_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.delete_connectivity_test: self._wrap_method( + self.delete_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self.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"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'ReachabilityServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py new file mode 100644 index 000000000000..aa84d74c181c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py @@ -0,0 +1,1714 @@ +# -*- 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.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseReachabilityServiceRestTransport +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 ReachabilityServiceRestInterceptor: + """Interceptor for ReachabilityService. + + 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 ReachabilityServiceRestTransport. + + .. code-block:: python + class MyCustomReachabilityServiceInterceptor(ReachabilityServiceRestInterceptor): + def pre_create_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_connectivity_tests(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_connectivity_tests(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_rerun_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_rerun_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ReachabilityServiceRestTransport(interceptor=MyCustomReachabilityServiceInterceptor()) + client = ReachabilityServiceClient(transport=transport) + + + """ + def pre_create_connectivity_test(self, request: reachability.CreateConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.CreateConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_create_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_delete_connectivity_test(self, request: reachability.DeleteConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.DeleteConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_delete_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_get_connectivity_test(self, request: reachability.GetConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.GetConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_get_connectivity_test(self, response: connectivity_test.ConnectivityTest) -> connectivity_test.ConnectivityTest: + """Post-rpc interceptor for get_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_list_connectivity_tests(self, request: reachability.ListConnectivityTestsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.ListConnectivityTestsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_connectivity_tests + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_list_connectivity_tests(self, response: reachability.ListConnectivityTestsResponse) -> reachability.ListConnectivityTestsResponse: + """Post-rpc interceptor for list_connectivity_tests + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_rerun_connectivity_test(self, request: reachability.RerunConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.RerunConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for rerun_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_rerun_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for rerun_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_update_connectivity_test(self, request: reachability.UpdateConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.UpdateConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_update_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ReachabilityServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ReachabilityServiceRestInterceptor + + +class ReachabilityServiceRestTransport(_BaseReachabilityServiceRestTransport): + """REST backend synchronous transport for ReachabilityService. + + The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + + 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 = 'networkmanagement.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[ReachabilityServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkmanagement.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 ReachabilityServiceRestInterceptor() + 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/global/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/global/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/global/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/global}/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 _CreateConnectivityTest(_BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.CreateConnectivityTest") + + @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: reachability.CreateConnectivityTestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create connectivity test method over HTTP. + + Args: + request (~.reachability.CreateConnectivityTestRequest): + The request object. Request for the ``CreateConnectivityTest`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_http_options() + request, metadata = self._interceptor.pre_create_connectivity_test(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._CreateConnectivityTest._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_connectivity_test(resp) + return resp + + class _DeleteConnectivityTest(_BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.DeleteConnectivityTest") + + @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: reachability.DeleteConnectivityTestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete connectivity test method over HTTP. + + Args: + request (~.reachability.DeleteConnectivityTestRequest): + The request object. Request for the ``DeleteConnectivityTest`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_http_options() + request, metadata = self._interceptor.pre_delete_connectivity_test(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._DeleteConnectivityTest._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_connectivity_test(resp) + return resp + + class _GetConnectivityTest(_BaseReachabilityServiceRestTransport._BaseGetConnectivityTest, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.GetConnectivityTest") + + @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: reachability.GetConnectivityTestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> connectivity_test.ConnectivityTest: + r"""Call the get connectivity test method over HTTP. + + Args: + request (~.reachability.GetConnectivityTestRequest): + The request object. Request for the ``GetConnectivityTest`` 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: + ~.connectivity_test.ConnectivityTest: + A Connectivity Test for a network + reachability analysis. + + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_http_options() + request, metadata = self._interceptor.pre_get_connectivity_test(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._GetConnectivityTest._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 = connectivity_test.ConnectivityTest() + pb_resp = connectivity_test.ConnectivityTest.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_connectivity_test(resp) + return resp + + class _ListConnectivityTests(_BaseReachabilityServiceRestTransport._BaseListConnectivityTests, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.ListConnectivityTests") + + @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: reachability.ListConnectivityTestsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> reachability.ListConnectivityTestsResponse: + r"""Call the list connectivity tests method over HTTP. + + Args: + request (~.reachability.ListConnectivityTestsRequest): + The request object. Request for the ``ListConnectivityTests`` 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: + ~.reachability.ListConnectivityTestsResponse: + Response for the ``ListConnectivityTests`` method. + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_http_options() + request, metadata = self._interceptor.pre_list_connectivity_tests(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._ListConnectivityTests._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 = reachability.ListConnectivityTestsResponse() + pb_resp = reachability.ListConnectivityTestsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_connectivity_tests(resp) + return resp + + class _RerunConnectivityTest(_BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.RerunConnectivityTest") + + @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: reachability.RerunConnectivityTestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the rerun connectivity test method over HTTP. + + Args: + request (~.reachability.RerunConnectivityTestRequest): + The request object. Request for the ``RerunConnectivityTest`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_http_options() + request, metadata = self._interceptor.pre_rerun_connectivity_test(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._RerunConnectivityTest._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_rerun_connectivity_test(resp) + return resp + + class _UpdateConnectivityTest(_BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.UpdateConnectivityTest") + + @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: reachability.UpdateConnectivityTestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update connectivity test method over HTTP. + + Args: + request (~.reachability.UpdateConnectivityTestRequest): + The request object. Request for the ``UpdateConnectivityTest`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_http_options() + request, metadata = self._interceptor.pre_update_connectivity_test(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._UpdateConnectivityTest._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_connectivity_test(resp) + return resp + + @property + def create_connectivity_test(self) -> Callable[ + [reachability.CreateConnectivityTestRequest], + 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._CreateConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_connectivity_test(self) -> Callable[ + [reachability.DeleteConnectivityTestRequest], + 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._DeleteConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_connectivity_test(self) -> Callable[ + [reachability.GetConnectivityTestRequest], + connectivity_test.ConnectivityTest]: + # 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._GetConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_connectivity_tests(self) -> Callable[ + [reachability.ListConnectivityTestsRequest], + reachability.ListConnectivityTestsResponse]: + # 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._ListConnectivityTests(self._session, self._host, self._interceptor) # type: ignore + + @property + def rerun_connectivity_test(self) -> Callable[ + [reachability.RerunConnectivityTestRequest], + 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._RerunConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_connectivity_test(self) -> Callable[ + [reachability.UpdateConnectivityTestRequest], + 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._UpdateConnectivityTest(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(_BaseReachabilityServiceRestTransport._BaseGetLocation, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseListLocations, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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 get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseReachabilityServiceRestTransport._BaseGetIamPolicy, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseReachabilityServiceRestTransport._BaseSetIamPolicy, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseReachabilityServiceRestTransport._BaseTestIamPermissions, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseReachabilityServiceRestTransport._BaseCancelOperation, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseDeleteOperation, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseGetOperation, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseListOperations, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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__=( + 'ReachabilityServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py new file mode 100644 index 000000000000..7dd2991844be --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py @@ -0,0 +1,588 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseReachabilityServiceRestTransport(ReachabilityServiceTransport): + """Base REST backend transport for ReachabilityService. + + 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 = 'networkmanagement.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: 'networkmanagement.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 _BaseCreateConnectivityTest: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "testId" : "", } + + @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/global}/connectivityTests', + 'body': 'resource', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.CreateConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteConnectivityTest: + 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/global/connectivityTests/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.DeleteConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetConnectivityTest: + 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/global/connectivityTests/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.GetConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListConnectivityTests: + 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/global}/connectivityTests', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.ListConnectivityTestsRequest.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(_BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRerunConnectivityTest: + 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/global/connectivityTests/*}:rerun', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.RerunConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateConnectivityTest: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{resource.name=projects/*/locations/global/connectivityTests/*}', + 'body': 'resource', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.UpdateConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/global/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/global/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/global/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/global}/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__=( + '_BaseReachabilityServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py new file mode 100644 index 000000000000..ce14d0c9af68 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py @@ -0,0 +1,114 @@ +# -*- 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 .connectivity_test import ( + ConnectivityTest, + Endpoint, + LatencyDistribution, + LatencyPercentile, + ProbingDetails, + ReachabilityDetails, +) +from .reachability import ( + CreateConnectivityTestRequest, + DeleteConnectivityTestRequest, + GetConnectivityTestRequest, + ListConnectivityTestsRequest, + ListConnectivityTestsResponse, + OperationMetadata, + RerunConnectivityTestRequest, + UpdateConnectivityTestRequest, +) +from .trace import ( + AbortInfo, + AppEngineVersionInfo, + CloudFunctionInfo, + CloudRunRevisionInfo, + CloudSQLInstanceInfo, + DeliverInfo, + DropInfo, + EndpointInfo, + FirewallInfo, + ForwardInfo, + ForwardingRuleInfo, + GKEMasterInfo, + GoogleServiceInfo, + InstanceInfo, + LoadBalancerBackend, + LoadBalancerBackendInfo, + LoadBalancerInfo, + NatInfo, + NetworkInfo, + ProxyConnectionInfo, + RedisClusterInfo, + RedisInstanceInfo, + RouteInfo, + ServerlessNegInfo, + Step, + StorageBucketInfo, + Trace, + VpcConnectorInfo, + VpnGatewayInfo, + VpnTunnelInfo, + LoadBalancerType, +) + +__all__ = ( + 'ConnectivityTest', + 'Endpoint', + 'LatencyDistribution', + 'LatencyPercentile', + 'ProbingDetails', + 'ReachabilityDetails', + 'CreateConnectivityTestRequest', + 'DeleteConnectivityTestRequest', + 'GetConnectivityTestRequest', + 'ListConnectivityTestsRequest', + 'ListConnectivityTestsResponse', + 'OperationMetadata', + 'RerunConnectivityTestRequest', + 'UpdateConnectivityTestRequest', + 'AbortInfo', + 'AppEngineVersionInfo', + 'CloudFunctionInfo', + 'CloudRunRevisionInfo', + 'CloudSQLInstanceInfo', + 'DeliverInfo', + 'DropInfo', + 'EndpointInfo', + 'FirewallInfo', + 'ForwardInfo', + 'ForwardingRuleInfo', + 'GKEMasterInfo', + 'GoogleServiceInfo', + 'InstanceInfo', + 'LoadBalancerBackend', + 'LoadBalancerBackendInfo', + 'LoadBalancerInfo', + 'NatInfo', + 'NetworkInfo', + 'ProxyConnectionInfo', + 'RedisClusterInfo', + 'RedisInstanceInfo', + 'RouteInfo', + 'ServerlessNegInfo', + 'Step', + 'StorageBucketInfo', + 'Trace', + 'VpcConnectorInfo', + 'VpnGatewayInfo', + 'VpnTunnelInfo', + 'LoadBalancerType', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py new file mode 100644 index 000000000000..5a3ba49e5693 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py @@ -0,0 +1,735 @@ +# -*- 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.network_management_v1.types import trace +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networkmanagement.v1', + manifest={ + 'ConnectivityTest', + 'Endpoint', + 'ReachabilityDetails', + 'LatencyPercentile', + 'LatencyDistribution', + 'ProbingDetails', + }, +) + + +class ConnectivityTest(proto.Message): + r"""A Connectivity Test for a network reachability analysis. + + Attributes: + name (str): + Identifier. Unique name of the resource using the form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + description (str): + The user-supplied description of the + Connectivity Test. Maximum of 512 characters. + source (google.cloud.network_management_v1.types.Endpoint): + Required. Source specification of the + Connectivity Test. + You can use a combination of source IP address, + virtual machine (VM) instance, or Compute Engine + network to uniquely identify the source + location. + + Examples: + + If the source IP address is an internal IP + address within a Google Cloud Virtual Private + Cloud (VPC) network, then you must also specify + the VPC network. Otherwise, specify the VM + instance, which already contains its internal IP + address and VPC network information. + + If the source of the test is within an + on-premises network, then you must provide the + destination VPC network. + + If the source endpoint is a Compute Engine VM + instance with multiple network interfaces, the + instance itself is not sufficient to identify + the endpoint. So, you must also specify the + source IP address or VPC network. + + A reachability analysis proceeds even if the + source location is ambiguous. However, the test + result may include endpoints that you don't + intend to test. + destination (google.cloud.network_management_v1.types.Endpoint): + Required. Destination specification of the + Connectivity Test. + You can use a combination of destination IP + address, Compute Engine VM instance, or VPC + network to uniquely identify the destination + location. + + Even if the destination IP address is not + unique, the source IP location is unique. + Usually, the analysis can infer the destination + endpoint from route information. + + If the destination you specify is a VM instance + and the instance has multiple network + interfaces, then you must also specify either a + destination IP address or VPC network to + identify the destination interface. + + A reachability analysis proceeds even if the + destination location is ambiguous. However, the + result can include endpoints that you don't + intend to test. + protocol (str): + IP Protocol of the test. When not provided, + "TCP" is assumed. + related_projects (MutableSequence[str]): + Other projects that may be relevant for + reachability analysis. This is applicable to + scenarios where a test can cross project + boundaries. + display_name (str): + Output only. The display name of a + Connectivity Test. + labels (MutableMapping[str, str]): + Resource labels to represent user-provided + metadata. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the test was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the test's + configuration was updated. + reachability_details (google.cloud.network_management_v1.types.ReachabilityDetails): + Output only. The reachability details of this + test from the latest run. The details are + updated when creating a new test, updating an + existing test, or triggering a one-time rerun of + an existing test. + probing_details (google.cloud.network_management_v1.types.ProbingDetails): + Output only. The probing details of this test + from the latest run, present for applicable + tests only. The details are updated when + creating a new test, updating an existing test, + or triggering a one-time rerun of an existing + test. + bypass_firewall_checks (bool): + Whether the test should skip firewall + checking. If not provided, we assume false. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + source: 'Endpoint' = proto.Field( + proto.MESSAGE, + number=3, + message='Endpoint', + ) + destination: 'Endpoint' = proto.Field( + proto.MESSAGE, + number=4, + message='Endpoint', + ) + protocol: str = proto.Field( + proto.STRING, + number=5, + ) + related_projects: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + display_name: str = proto.Field( + proto.STRING, + number=7, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + reachability_details: 'ReachabilityDetails' = proto.Field( + proto.MESSAGE, + number=12, + message='ReachabilityDetails', + ) + probing_details: 'ProbingDetails' = proto.Field( + proto.MESSAGE, + number=14, + message='ProbingDetails', + ) + bypass_firewall_checks: bool = proto.Field( + proto.BOOL, + number=17, + ) + + +class Endpoint(proto.Message): + r"""Source or destination of the Connectivity Test. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + ip_address (str): + The IP address of the endpoint, which can be + an external or internal IP. + port (int): + The IP protocol port of the endpoint. + Only applicable when protocol is TCP or UDP. + instance (str): + A Compute Engine instance URI. + forwarding_rule (str): + A forwarding rule and its corresponding IP + address represent the frontend configuration of + a Google Cloud load balancer. Forwarding rules + are also used for protocol forwarding, Private + Service Connect and other network services to + provide forwarding information in the control + plane. Format: + + projects/{project}/global/forwardingRules/{id} + or + projects/{project}/regions/{region}/forwardingRules/{id} + forwarding_rule_target (google.cloud.network_management_v1.types.Endpoint.ForwardingRuleTarget): + Output only. Specifies the type of the target + of the forwarding rule. + + This field is a member of `oneof`_ ``_forwarding_rule_target``. + load_balancer_id (str): + Output only. ID of the load balancer the + forwarding rule points to. Empty for forwarding + rules not related to load balancers. + + This field is a member of `oneof`_ ``_load_balancer_id``. + load_balancer_type (google.cloud.network_management_v1.types.LoadBalancerType): + Output only. Type of the load balancer the + forwarding rule points to. + + This field is a member of `oneof`_ ``_load_balancer_type``. + gke_master_cluster (str): + A cluster URI for `Google Kubernetes Engine cluster control + plane `__. + fqdn (str): + DNS endpoint of `Google Kubernetes Engine cluster control + plane `__. + Requires gke_master_cluster to be set, can't be used + simultaneoulsly with ip_address or network. Applicable only + to destination endpoint. + cloud_sql_instance (str): + A `Cloud SQL `__ instance URI. + redis_instance (str): + A `Redis + Instance `__ + URI. + redis_cluster (str): + A `Redis + Cluster `__ + URI. + cloud_function (google.cloud.network_management_v1.types.Endpoint.CloudFunctionEndpoint): + A `Cloud Function `__. + app_engine_version (google.cloud.network_management_v1.types.Endpoint.AppEngineVersionEndpoint): + An `App Engine `__ + `service + version `__. + cloud_run_revision (google.cloud.network_management_v1.types.Endpoint.CloudRunRevisionEndpoint): + A `Cloud Run `__ + `revision `__ + network (str): + A Compute Engine network URI. + network_type (google.cloud.network_management_v1.types.Endpoint.NetworkType): + Type of the network where the endpoint is + located. Applicable only to source endpoint, as + destination network type can be inferred from + the source. + project_id (str): + Project ID where the endpoint is located. + The Project ID can be derived from the URI if + you provide a VM instance or network URI. + The following are two cases where you must + provide the project ID: + + 1. Only the IP address is specified, and the IP + address is within a Google Cloud project. + 2. When you are using Shared VPC and the IP + address that you provide is from the service + project. In this case, the network that the + IP address resides in is defined in the host + project. + """ + class NetworkType(proto.Enum): + r"""The type definition of an endpoint's network. Use one of the + following choices: + + Values: + NETWORK_TYPE_UNSPECIFIED (0): + Default type if unspecified. + GCP_NETWORK (1): + A network hosted within Google Cloud. + To receive more detailed output, specify the URI + for the source or destination network. + NON_GCP_NETWORK (2): + A network hosted outside of Google Cloud. + This can be an on-premises network, or a network + hosted by another cloud provider. + """ + NETWORK_TYPE_UNSPECIFIED = 0 + GCP_NETWORK = 1 + NON_GCP_NETWORK = 2 + + class ForwardingRuleTarget(proto.Enum): + r"""Type of the target of a forwarding rule. + + Values: + FORWARDING_RULE_TARGET_UNSPECIFIED (0): + Forwarding rule target is unknown. + INSTANCE (1): + Compute Engine instance for protocol + forwarding. + LOAD_BALANCER (2): + Load Balancer. The specific type can be found from + [load_balancer_type] + [google.cloud.networkmanagement.v1.Endpoint.load_balancer_type]. + VPN_GATEWAY (3): + Classic Cloud VPN Gateway. + PSC (4): + Forwarding Rule is a Private Service Connect + endpoint. + """ + FORWARDING_RULE_TARGET_UNSPECIFIED = 0 + INSTANCE = 1 + LOAD_BALANCER = 2 + VPN_GATEWAY = 3 + PSC = 4 + + class CloudFunctionEndpoint(proto.Message): + r"""Wrapper for Cloud Function attributes. + + Attributes: + uri (str): + A `Cloud Function `__ + name. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + class AppEngineVersionEndpoint(proto.Message): + r"""Wrapper for the App Engine service version attributes. + + Attributes: + uri (str): + An `App Engine `__ + `service + version `__ + name. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + class CloudRunRevisionEndpoint(proto.Message): + r"""Wrapper for Cloud Run revision attributes. + + Attributes: + uri (str): + A `Cloud Run `__ + `revision `__ + URI. The format is: + projects/{project}/locations/{location}/revisions/{revision} + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + ip_address: str = proto.Field( + proto.STRING, + number=1, + ) + port: int = proto.Field( + proto.INT32, + number=2, + ) + instance: str = proto.Field( + proto.STRING, + number=3, + ) + forwarding_rule: str = proto.Field( + proto.STRING, + number=13, + ) + forwarding_rule_target: ForwardingRuleTarget = proto.Field( + proto.ENUM, + number=14, + optional=True, + enum=ForwardingRuleTarget, + ) + load_balancer_id: str = proto.Field( + proto.STRING, + number=15, + optional=True, + ) + load_balancer_type: trace.LoadBalancerType = proto.Field( + proto.ENUM, + number=16, + optional=True, + enum=trace.LoadBalancerType, + ) + gke_master_cluster: str = proto.Field( + proto.STRING, + number=7, + ) + fqdn: str = proto.Field( + proto.STRING, + number=19, + ) + cloud_sql_instance: str = proto.Field( + proto.STRING, + number=8, + ) + redis_instance: str = proto.Field( + proto.STRING, + number=17, + ) + redis_cluster: str = proto.Field( + proto.STRING, + number=18, + ) + cloud_function: CloudFunctionEndpoint = proto.Field( + proto.MESSAGE, + number=10, + message=CloudFunctionEndpoint, + ) + app_engine_version: AppEngineVersionEndpoint = proto.Field( + proto.MESSAGE, + number=11, + message=AppEngineVersionEndpoint, + ) + cloud_run_revision: CloudRunRevisionEndpoint = proto.Field( + proto.MESSAGE, + number=12, + message=CloudRunRevisionEndpoint, + ) + network: str = proto.Field( + proto.STRING, + number=4, + ) + network_type: NetworkType = proto.Field( + proto.ENUM, + number=5, + enum=NetworkType, + ) + project_id: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ReachabilityDetails(proto.Message): + r"""Results of the configuration analysis from the last run of + the test. + + Attributes: + result (google.cloud.network_management_v1.types.ReachabilityDetails.Result): + The overall result of the test's + configuration analysis. + verify_time (google.protobuf.timestamp_pb2.Timestamp): + The time of the configuration analysis. + error (google.rpc.status_pb2.Status): + The details of a failure or a cancellation of + reachability analysis. + traces (MutableSequence[google.cloud.network_management_v1.types.Trace]): + Result may contain a list of traces if a test + has multiple possible paths in the network, such + as when destination endpoint is a load balancer + with multiple backends. + """ + class Result(proto.Enum): + r"""The overall result of the test's configuration analysis. + + Values: + RESULT_UNSPECIFIED (0): + No result was specified. + REACHABLE (1): + Possible scenarios are: + + - The configuration analysis determined that a packet + originating from the source is expected to reach the + destination. + - The analysis didn't complete because the user lacks + permission for some of the resources in the trace. + However, at the time the user's permission became + insufficient, the trace had been successful so far. + UNREACHABLE (2): + A packet originating from the source is + expected to be dropped before reaching the + destination. + AMBIGUOUS (4): + The source and destination endpoints do not + uniquely identify the test location in the + network, and the reachability result contains + multiple traces. For some traces, a packet could + be delivered, and for others, it would not be. + This result is also assigned to configuration + analysis of return path if on its own it should + be REACHABLE, but configuration analysis of + forward path is AMBIGUOUS. + UNDETERMINED (5): + The configuration analysis did not complete. Possible + reasons are: + + - A permissions error occurred--for example, the user might + not have read permission for all of the resources named + in the test. + - An internal error occurred. + - The analyzer received an invalid or unsupported argument + or was unable to identify a known endpoint. + """ + RESULT_UNSPECIFIED = 0 + REACHABLE = 1 + UNREACHABLE = 2 + AMBIGUOUS = 4 + UNDETERMINED = 5 + + result: Result = proto.Field( + proto.ENUM, + number=1, + enum=Result, + ) + verify_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + traces: MutableSequence[trace.Trace] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=trace.Trace, + ) + + +class LatencyPercentile(proto.Message): + r"""Latency percentile rank and value. + + Attributes: + percent (int): + Percentage of samples this data point applies + to. + latency_micros (int): + percent-th percentile of latency observed, in + microseconds. Fraction of percent/100 of samples + have latency lower or equal to the value of this + field. + """ + + percent: int = proto.Field( + proto.INT32, + number=1, + ) + latency_micros: int = proto.Field( + proto.INT64, + number=2, + ) + + +class LatencyDistribution(proto.Message): + r"""Describes measured latency distribution. + + Attributes: + latency_percentiles (MutableSequence[google.cloud.network_management_v1.types.LatencyPercentile]): + Representative latency percentiles. + """ + + latency_percentiles: MutableSequence['LatencyPercentile'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='LatencyPercentile', + ) + + +class ProbingDetails(proto.Message): + r"""Results of active probing from the last run of the test. + + Attributes: + result (google.cloud.network_management_v1.types.ProbingDetails.ProbingResult): + The overall result of active probing. + verify_time (google.protobuf.timestamp_pb2.Timestamp): + The time that reachability was assessed + through active probing. + error (google.rpc.status_pb2.Status): + Details about an internal failure or the + cancellation of active probing. + abort_cause (google.cloud.network_management_v1.types.ProbingDetails.ProbingAbortCause): + The reason probing was aborted. + sent_probe_count (int): + Number of probes sent. + successful_probe_count (int): + Number of probes that reached the + destination. + endpoint_info (google.cloud.network_management_v1.types.EndpointInfo): + The source and destination endpoints derived + from the test input and used for active probing. + probing_latency (google.cloud.network_management_v1.types.LatencyDistribution): + Latency as measured by active probing in one + direction: from the source to the destination + endpoint. + destination_egress_location (google.cloud.network_management_v1.types.ProbingDetails.EdgeLocation): + The EdgeLocation from which a packet destined + for/originating from the internet will egress/ingress the + Google network. This will only be populated for a + connectivity test which has an internet destination/source + address. The absence of this field *must not* be used as an + indication that the destination/source is part of the Google + network. + """ + class ProbingResult(proto.Enum): + r"""Overall probing result of the test. + + Values: + PROBING_RESULT_UNSPECIFIED (0): + No result was specified. + REACHABLE (1): + At least 95% of packets reached the + destination. + UNREACHABLE (2): + No packets reached the destination. + REACHABILITY_INCONSISTENT (3): + Less than 95% of packets reached the + destination. + UNDETERMINED (4): + Reachability could not be determined. Possible reasons are: + + - The user lacks permission to access some of the network + resources required to run the test. + - No valid source endpoint could be derived from the + request. + - An internal error occurred. + """ + PROBING_RESULT_UNSPECIFIED = 0 + REACHABLE = 1 + UNREACHABLE = 2 + REACHABILITY_INCONSISTENT = 3 + UNDETERMINED = 4 + + class ProbingAbortCause(proto.Enum): + r"""Abort cause types. + + Values: + PROBING_ABORT_CAUSE_UNSPECIFIED (0): + No reason was specified. + PERMISSION_DENIED (1): + The user lacks permission to access some of + the network resources required to run the test. + NO_SOURCE_LOCATION (2): + No valid source endpoint could be derived + from the request. + """ + PROBING_ABORT_CAUSE_UNSPECIFIED = 0 + PERMISSION_DENIED = 1 + NO_SOURCE_LOCATION = 2 + + class EdgeLocation(proto.Message): + r"""Representation of a network edge location as per + https://cloud.google.com/vpc/docs/edge-locations. + + Attributes: + metropolitan_area (str): + Name of the metropolitan area. + """ + + metropolitan_area: str = proto.Field( + proto.STRING, + number=1, + ) + + result: ProbingResult = proto.Field( + proto.ENUM, + number=1, + enum=ProbingResult, + ) + verify_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + abort_cause: ProbingAbortCause = proto.Field( + proto.ENUM, + number=4, + enum=ProbingAbortCause, + ) + sent_probe_count: int = proto.Field( + proto.INT32, + number=5, + ) + successful_probe_count: int = proto.Field( + proto.INT32, + number=6, + ) + endpoint_info: trace.EndpointInfo = proto.Field( + proto.MESSAGE, + number=7, + message=trace.EndpointInfo, + ) + probing_latency: 'LatencyDistribution' = proto.Field( + proto.MESSAGE, + number=8, + message='LatencyDistribution', + ) + destination_egress_location: EdgeLocation = proto.Field( + proto.MESSAGE, + number=9, + message=EdgeLocation, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py new file mode 100644 index 000000000000..ed3cdf469712 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py @@ -0,0 +1,293 @@ +# -*- 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.network_management_v1.types import connectivity_test +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networkmanagement.v1', + manifest={ + 'ListConnectivityTestsRequest', + 'ListConnectivityTestsResponse', + 'GetConnectivityTestRequest', + 'CreateConnectivityTestRequest', + 'UpdateConnectivityTestRequest', + 'DeleteConnectivityTestRequest', + 'RerunConnectivityTestRequest', + 'OperationMetadata', + }, +) + + +class ListConnectivityTestsRequest(proto.Message): + r"""Request for the ``ListConnectivityTests`` method. + + Attributes: + parent (str): + Required. The parent resource of the Connectivity Tests: + ``projects/{project_id}/locations/global`` + page_size (int): + Number of ``ConnectivityTests`` to return. + page_token (str): + Page token from an earlier query, as returned in + ``next_page_token``. + filter (str): + Lists the ``ConnectivityTests`` that match the filter + expression. A filter expression filters the resources listed + in the response. The expression must be of the form + `` `` where operators: ``<``, + ``>``, ``<=``, ``>=``, ``!=``, ``=``, ``:`` are supported + (colon ``:`` represents a HAS operator which is roughly + synonymous with equality). can refer to a proto or JSON + field, or a synthetic field. Field names can be camelCase or + snake_case. + + Examples: + + - Filter by name: name = + "projects/proj-1/locations/global/connectivityTests/test-1 + + - Filter by labels: + + - Resources that have a key called ``foo`` labels.foo:\* + - Resources that have a key called ``foo`` whose value + is ``bar`` labels.foo = bar + order_by (str): + Field to use to sort the list. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListConnectivityTestsResponse(proto.Message): + r"""Response for the ``ListConnectivityTests`` method. + + Attributes: + resources (MutableSequence[google.cloud.network_management_v1.types.ConnectivityTest]): + List of Connectivity Tests. + next_page_token (str): + Page token to fetch the next set of + Connectivity Tests. + unreachable (MutableSequence[str]): + Locations that could not be reached (when querying all + locations with ``-``). + """ + + @property + def raw_page(self): + return self + + resources: MutableSequence[connectivity_test.ConnectivityTest] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=connectivity_test.ConnectivityTest, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetConnectivityTestRequest(proto.Message): + r"""Request for the ``GetConnectivityTest`` method. + + Attributes: + name (str): + Required. ``ConnectivityTest`` resource name using the form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateConnectivityTestRequest(proto.Message): + r"""Request for the ``CreateConnectivityTest`` method. + + Attributes: + parent (str): + Required. The parent resource of the Connectivity Test to + create: ``projects/{project_id}/locations/global`` + test_id (str): + Required. The logical name of the Connectivity Test in your + project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-40 characters. + - Must end with a number or a letter. + - Must be unique within the customer project + resource (google.cloud.network_management_v1.types.ConnectivityTest): + Required. A ``ConnectivityTest`` resource + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + test_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource: connectivity_test.ConnectivityTest = proto.Field( + proto.MESSAGE, + number=3, + message=connectivity_test.ConnectivityTest, + ) + + +class UpdateConnectivityTestRequest(proto.Message): + r"""Request for the ``UpdateConnectivityTest`` method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. At least + one path must be supplied in this field. + resource (google.cloud.network_management_v1.types.ConnectivityTest): + Required. Only fields specified in update_mask are updated. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + resource: connectivity_test.ConnectivityTest = proto.Field( + proto.MESSAGE, + number=2, + message=connectivity_test.ConnectivityTest, + ) + + +class DeleteConnectivityTestRequest(proto.Message): + r"""Request for the ``DeleteConnectivityTest`` method. + + Attributes: + name (str): + Required. Connectivity Test resource name using the form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RerunConnectivityTestRequest(proto.Message): + r"""Request for the ``RerunConnectivityTest`` method. + + Attributes: + name (str): + Required. Connectivity Test resource name using the form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class OperationMetadata(proto.Message): + r"""Metadata describing an [Operation][google.longrunning.Operation] + + 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): + Target of the operation - for example + projects/project-1/locations/global/connectivityTests/test-1 + verb (str): + Name of the verb executed by the operation. + status_detail (str): + Human-readable status of the operation, if + any. + cancel_requested (bool): + Specifies if cancellation was requested for + the operation. + api_version (str): + API version. + """ + + 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_detail: str = proto.Field( + proto.STRING, + number=5, + ) + cancel_requested: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py new file mode 100644 index 000000000000..78741f3894e1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py @@ -0,0 +1,3164 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.networkmanagement.v1', + manifest={ + 'LoadBalancerType', + 'Trace', + 'Step', + 'InstanceInfo', + 'NetworkInfo', + 'FirewallInfo', + 'RouteInfo', + 'GoogleServiceInfo', + 'ForwardingRuleInfo', + 'LoadBalancerInfo', + 'LoadBalancerBackend', + 'VpnGatewayInfo', + 'VpnTunnelInfo', + 'EndpointInfo', + 'DeliverInfo', + 'ForwardInfo', + 'AbortInfo', + 'DropInfo', + 'GKEMasterInfo', + 'CloudSQLInstanceInfo', + 'RedisInstanceInfo', + 'RedisClusterInfo', + 'CloudFunctionInfo', + 'CloudRunRevisionInfo', + 'AppEngineVersionInfo', + 'VpcConnectorInfo', + 'NatInfo', + 'ProxyConnectionInfo', + 'LoadBalancerBackendInfo', + 'StorageBucketInfo', + 'ServerlessNegInfo', + }, +) + + +class LoadBalancerType(proto.Enum): + r"""Type of a load balancer. For more information, see `Summary of + Google Cloud load + balancers `__. + + Values: + LOAD_BALANCER_TYPE_UNSPECIFIED (0): + Forwarding rule points to a different target + than a load balancer or a load balancer type is + unknown. + HTTPS_ADVANCED_LOAD_BALANCER (1): + Global external HTTP(S) load balancer. + HTTPS_LOAD_BALANCER (2): + Global external HTTP(S) load balancer + (classic) + REGIONAL_HTTPS_LOAD_BALANCER (3): + Regional external HTTP(S) load balancer. + INTERNAL_HTTPS_LOAD_BALANCER (4): + Internal HTTP(S) load balancer. + SSL_PROXY_LOAD_BALANCER (5): + External SSL proxy load balancer. + TCP_PROXY_LOAD_BALANCER (6): + External TCP proxy load balancer. + INTERNAL_TCP_PROXY_LOAD_BALANCER (7): + Internal regional TCP proxy load balancer. + NETWORK_LOAD_BALANCER (8): + External TCP/UDP Network load balancer. + LEGACY_NETWORK_LOAD_BALANCER (9): + Target-pool based external TCP/UDP Network + load balancer. + TCP_UDP_INTERNAL_LOAD_BALANCER (10): + Internal TCP/UDP load balancer. + """ + LOAD_BALANCER_TYPE_UNSPECIFIED = 0 + HTTPS_ADVANCED_LOAD_BALANCER = 1 + HTTPS_LOAD_BALANCER = 2 + REGIONAL_HTTPS_LOAD_BALANCER = 3 + INTERNAL_HTTPS_LOAD_BALANCER = 4 + SSL_PROXY_LOAD_BALANCER = 5 + TCP_PROXY_LOAD_BALANCER = 6 + INTERNAL_TCP_PROXY_LOAD_BALANCER = 7 + NETWORK_LOAD_BALANCER = 8 + LEGACY_NETWORK_LOAD_BALANCER = 9 + TCP_UDP_INTERNAL_LOAD_BALANCER = 10 + + +class Trace(proto.Message): + r"""Trace represents one simulated packet forwarding path. + + - Each trace contains multiple ordered steps. + - Each step is in a particular state with associated configuration. + - State is categorized as final or non-final states. + - Each final state has a reason associated. + - Each trace must end with a final state (the last step). + + :: + + |---------------------Trace----------------------| + Step1(State) Step2(State) --- StepN(State(final)) + + Attributes: + endpoint_info (google.cloud.network_management_v1.types.EndpointInfo): + Derived from the source and destination endpoints definition + specified by user request, and validated by the data plane + model. If there are multiple traces starting from different + source locations, then the endpoint_info may be different + between traces. + steps (MutableSequence[google.cloud.network_management_v1.types.Step]): + A trace of a test contains multiple steps + from the initial state to the final state + (delivered, dropped, forwarded, or aborted). + + The steps are ordered by the processing sequence + within the simulated network state machine. It + is critical to preserve the order of the steps + and avoid reordering or sorting them. + forward_trace_id (int): + ID of trace. For forward traces, this ID is + unique for each trace. For return traces, it + matches ID of associated forward trace. A single + forward trace can be associated with none, one + or more than one return trace. + """ + + endpoint_info: 'EndpointInfo' = proto.Field( + proto.MESSAGE, + number=1, + message='EndpointInfo', + ) + steps: MutableSequence['Step'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Step', + ) + forward_trace_id: int = proto.Field( + proto.INT32, + number=4, + ) + + +class Step(proto.Message): + r"""A simulated forwarding path is composed of multiple steps. + Each step has a well-defined state and an associated + configuration. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + description (str): + A description of the step. Usually this is a + summary of the state. + state (google.cloud.network_management_v1.types.Step.State): + Each step is in one of the pre-defined + states. + causes_drop (bool): + This is a step that leads to the final state + Drop. + project_id (str): + Project ID that contains the configuration + this step is validating. + instance (google.cloud.network_management_v1.types.InstanceInfo): + Display information of a Compute Engine + instance. + + This field is a member of `oneof`_ ``step_info``. + firewall (google.cloud.network_management_v1.types.FirewallInfo): + Display information of a Compute Engine + firewall rule. + + This field is a member of `oneof`_ ``step_info``. + route (google.cloud.network_management_v1.types.RouteInfo): + Display information of a Compute Engine + route. + + This field is a member of `oneof`_ ``step_info``. + endpoint (google.cloud.network_management_v1.types.EndpointInfo): + Display information of the source and + destination under analysis. The endpoint + information in an intermediate state may differ + with the initial input, as it might be modified + by state like NAT, or Connection Proxy. + + This field is a member of `oneof`_ ``step_info``. + google_service (google.cloud.network_management_v1.types.GoogleServiceInfo): + Display information of a Google service + + This field is a member of `oneof`_ ``step_info``. + forwarding_rule (google.cloud.network_management_v1.types.ForwardingRuleInfo): + Display information of a Compute Engine + forwarding rule. + + This field is a member of `oneof`_ ``step_info``. + vpn_gateway (google.cloud.network_management_v1.types.VpnGatewayInfo): + Display information of a Compute Engine VPN + gateway. + + This field is a member of `oneof`_ ``step_info``. + vpn_tunnel (google.cloud.network_management_v1.types.VpnTunnelInfo): + Display information of a Compute Engine VPN + tunnel. + + This field is a member of `oneof`_ ``step_info``. + vpc_connector (google.cloud.network_management_v1.types.VpcConnectorInfo): + Display information of a VPC connector. + + This field is a member of `oneof`_ ``step_info``. + deliver (google.cloud.network_management_v1.types.DeliverInfo): + Display information of the final state + "deliver" and reason. + + This field is a member of `oneof`_ ``step_info``. + forward (google.cloud.network_management_v1.types.ForwardInfo): + Display information of the final state + "forward" and reason. + + This field is a member of `oneof`_ ``step_info``. + abort (google.cloud.network_management_v1.types.AbortInfo): + Display information of the final state + "abort" and reason. + + This field is a member of `oneof`_ ``step_info``. + drop (google.cloud.network_management_v1.types.DropInfo): + Display information of the final state "drop" + and reason. + + This field is a member of `oneof`_ ``step_info``. + load_balancer (google.cloud.network_management_v1.types.LoadBalancerInfo): + Display information of the load balancers. Deprecated in + favor of the ``load_balancer_backend_info`` field, not used + in new tests. + + This field is a member of `oneof`_ ``step_info``. + network (google.cloud.network_management_v1.types.NetworkInfo): + Display information of a Google Cloud + network. + + This field is a member of `oneof`_ ``step_info``. + gke_master (google.cloud.network_management_v1.types.GKEMasterInfo): + Display information of a Google Kubernetes + Engine cluster master. + + This field is a member of `oneof`_ ``step_info``. + cloud_sql_instance (google.cloud.network_management_v1.types.CloudSQLInstanceInfo): + Display information of a Cloud SQL instance. + + This field is a member of `oneof`_ ``step_info``. + redis_instance (google.cloud.network_management_v1.types.RedisInstanceInfo): + Display information of a Redis Instance. + + This field is a member of `oneof`_ ``step_info``. + redis_cluster (google.cloud.network_management_v1.types.RedisClusterInfo): + Display information of a Redis Cluster. + + This field is a member of `oneof`_ ``step_info``. + cloud_function (google.cloud.network_management_v1.types.CloudFunctionInfo): + Display information of a Cloud Function. + + This field is a member of `oneof`_ ``step_info``. + app_engine_version (google.cloud.network_management_v1.types.AppEngineVersionInfo): + Display information of an App Engine service + version. + + This field is a member of `oneof`_ ``step_info``. + cloud_run_revision (google.cloud.network_management_v1.types.CloudRunRevisionInfo): + Display information of a Cloud Run revision. + + This field is a member of `oneof`_ ``step_info``. + nat (google.cloud.network_management_v1.types.NatInfo): + Display information of a NAT. + + This field is a member of `oneof`_ ``step_info``. + proxy_connection (google.cloud.network_management_v1.types.ProxyConnectionInfo): + Display information of a ProxyConnection. + + This field is a member of `oneof`_ ``step_info``. + load_balancer_backend_info (google.cloud.network_management_v1.types.LoadBalancerBackendInfo): + Display information of a specific load + balancer backend. + + This field is a member of `oneof`_ ``step_info``. + storage_bucket (google.cloud.network_management_v1.types.StorageBucketInfo): + Display information of a Storage Bucket. Used + only for return traces. + + This field is a member of `oneof`_ ``step_info``. + serverless_neg (google.cloud.network_management_v1.types.ServerlessNegInfo): + Display information of a Serverless network + endpoint group backend. Used only for return + traces. + + This field is a member of `oneof`_ ``step_info``. + """ + class State(proto.Enum): + r"""Type of states that are defined in the network state machine. + Each step in the packet trace is in a specific state. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + START_FROM_INSTANCE (1): + Initial state: packet originating from a + Compute Engine instance. An InstanceInfo is + populated with starting instance information. + START_FROM_INTERNET (2): + Initial state: packet originating from the + internet. The endpoint information is populated. + START_FROM_GOOGLE_SERVICE (27): + Initial state: packet originating from a Google service. The + google_service information is populated. + START_FROM_PRIVATE_NETWORK (3): + Initial state: packet originating from a VPC + or on-premises network with internal source IP. + If the source is a VPC network visible to the + user, a NetworkInfo is populated with details of + the network. + START_FROM_GKE_MASTER (21): + Initial state: packet originating from a + Google Kubernetes Engine cluster master. A + GKEMasterInfo is populated with starting + instance information. + START_FROM_CLOUD_SQL_INSTANCE (22): + Initial state: packet originating from a + Cloud SQL instance. A CloudSQLInstanceInfo is + populated with starting instance information. + START_FROM_REDIS_INSTANCE (32): + Initial state: packet originating from a + Redis instance. A RedisInstanceInfo is populated + with starting instance information. + START_FROM_REDIS_CLUSTER (33): + Initial state: packet originating from a + Redis Cluster. A RedisClusterInfo is populated + with starting Cluster information. + START_FROM_CLOUD_FUNCTION (23): + Initial state: packet originating from a + Cloud Function. A CloudFunctionInfo is populated + with starting function information. + START_FROM_APP_ENGINE_VERSION (25): + Initial state: packet originating from an App + Engine service version. An AppEngineVersionInfo + is populated with starting version information. + START_FROM_CLOUD_RUN_REVISION (26): + Initial state: packet originating from a + Cloud Run revision. A CloudRunRevisionInfo is + populated with starting revision information. + START_FROM_STORAGE_BUCKET (29): + Initial state: packet originating from a Storage Bucket. + Used only for return traces. The storage_bucket information + is populated. + START_FROM_PSC_PUBLISHED_SERVICE (30): + Initial state: packet originating from a + published service that uses Private Service + Connect. Used only for return traces. + START_FROM_SERVERLESS_NEG (31): + Initial state: packet originating from a serverless network + endpoint group backend. Used only for return traces. The + serverless_neg information is populated. + APPLY_INGRESS_FIREWALL_RULE (4): + Config checking state: verify ingress + firewall rule. + APPLY_EGRESS_FIREWALL_RULE (5): + Config checking state: verify egress firewall + rule. + APPLY_ROUTE (6): + Config checking state: verify route. + APPLY_FORWARDING_RULE (7): + Config checking state: match forwarding rule. + ANALYZE_LOAD_BALANCER_BACKEND (28): + Config checking state: verify load balancer + backend configuration. + SPOOFING_APPROVED (8): + Config checking state: packet sent or + received under foreign IP address and allowed. + ARRIVE_AT_INSTANCE (9): + Forwarding state: arriving at a Compute + Engine instance. + ARRIVE_AT_INTERNAL_LOAD_BALANCER (10): + Forwarding state: arriving at a Compute + Engine internal load balancer. + ARRIVE_AT_EXTERNAL_LOAD_BALANCER (11): + Forwarding state: arriving at a Compute + Engine external load balancer. + ARRIVE_AT_VPN_GATEWAY (12): + Forwarding state: arriving at a Cloud VPN + gateway. + ARRIVE_AT_VPN_TUNNEL (13): + Forwarding state: arriving at a Cloud VPN + tunnel. + ARRIVE_AT_VPC_CONNECTOR (24): + Forwarding state: arriving at a VPC + connector. + NAT (14): + Transition state: packet header translated. + PROXY_CONNECTION (15): + Transition state: original connection is + terminated and a new proxied connection is + initiated. + DELIVER (16): + Final state: packet could be delivered. + DROP (17): + Final state: packet could be dropped. + FORWARD (18): + Final state: packet could be forwarded to a + network with an unknown configuration. + ABORT (19): + Final state: analysis is aborted. + VIEWER_PERMISSION_MISSING (20): + Special state: viewer of the test result does + not have permission to see the configuration in + this step. + """ + STATE_UNSPECIFIED = 0 + START_FROM_INSTANCE = 1 + START_FROM_INTERNET = 2 + START_FROM_GOOGLE_SERVICE = 27 + START_FROM_PRIVATE_NETWORK = 3 + START_FROM_GKE_MASTER = 21 + START_FROM_CLOUD_SQL_INSTANCE = 22 + START_FROM_REDIS_INSTANCE = 32 + START_FROM_REDIS_CLUSTER = 33 + START_FROM_CLOUD_FUNCTION = 23 + START_FROM_APP_ENGINE_VERSION = 25 + START_FROM_CLOUD_RUN_REVISION = 26 + START_FROM_STORAGE_BUCKET = 29 + START_FROM_PSC_PUBLISHED_SERVICE = 30 + START_FROM_SERVERLESS_NEG = 31 + APPLY_INGRESS_FIREWALL_RULE = 4 + APPLY_EGRESS_FIREWALL_RULE = 5 + APPLY_ROUTE = 6 + APPLY_FORWARDING_RULE = 7 + ANALYZE_LOAD_BALANCER_BACKEND = 28 + SPOOFING_APPROVED = 8 + ARRIVE_AT_INSTANCE = 9 + ARRIVE_AT_INTERNAL_LOAD_BALANCER = 10 + ARRIVE_AT_EXTERNAL_LOAD_BALANCER = 11 + ARRIVE_AT_VPN_GATEWAY = 12 + ARRIVE_AT_VPN_TUNNEL = 13 + ARRIVE_AT_VPC_CONNECTOR = 24 + NAT = 14 + PROXY_CONNECTION = 15 + DELIVER = 16 + DROP = 17 + FORWARD = 18 + ABORT = 19 + VIEWER_PERMISSION_MISSING = 20 + + description: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + causes_drop: bool = proto.Field( + proto.BOOL, + number=3, + ) + project_id: str = proto.Field( + proto.STRING, + number=4, + ) + instance: 'InstanceInfo' = proto.Field( + proto.MESSAGE, + number=5, + oneof='step_info', + message='InstanceInfo', + ) + firewall: 'FirewallInfo' = proto.Field( + proto.MESSAGE, + number=6, + oneof='step_info', + message='FirewallInfo', + ) + route: 'RouteInfo' = proto.Field( + proto.MESSAGE, + number=7, + oneof='step_info', + message='RouteInfo', + ) + endpoint: 'EndpointInfo' = proto.Field( + proto.MESSAGE, + number=8, + oneof='step_info', + message='EndpointInfo', + ) + google_service: 'GoogleServiceInfo' = proto.Field( + proto.MESSAGE, + number=24, + oneof='step_info', + message='GoogleServiceInfo', + ) + forwarding_rule: 'ForwardingRuleInfo' = proto.Field( + proto.MESSAGE, + number=9, + oneof='step_info', + message='ForwardingRuleInfo', + ) + vpn_gateway: 'VpnGatewayInfo' = proto.Field( + proto.MESSAGE, + number=10, + oneof='step_info', + message='VpnGatewayInfo', + ) + vpn_tunnel: 'VpnTunnelInfo' = proto.Field( + proto.MESSAGE, + number=11, + oneof='step_info', + message='VpnTunnelInfo', + ) + vpc_connector: 'VpcConnectorInfo' = proto.Field( + proto.MESSAGE, + number=21, + oneof='step_info', + message='VpcConnectorInfo', + ) + deliver: 'DeliverInfo' = proto.Field( + proto.MESSAGE, + number=12, + oneof='step_info', + message='DeliverInfo', + ) + forward: 'ForwardInfo' = proto.Field( + proto.MESSAGE, + number=13, + oneof='step_info', + message='ForwardInfo', + ) + abort: 'AbortInfo' = proto.Field( + proto.MESSAGE, + number=14, + oneof='step_info', + message='AbortInfo', + ) + drop: 'DropInfo' = proto.Field( + proto.MESSAGE, + number=15, + oneof='step_info', + message='DropInfo', + ) + load_balancer: 'LoadBalancerInfo' = proto.Field( + proto.MESSAGE, + number=16, + oneof='step_info', + message='LoadBalancerInfo', + ) + network: 'NetworkInfo' = proto.Field( + proto.MESSAGE, + number=17, + oneof='step_info', + message='NetworkInfo', + ) + gke_master: 'GKEMasterInfo' = proto.Field( + proto.MESSAGE, + number=18, + oneof='step_info', + message='GKEMasterInfo', + ) + cloud_sql_instance: 'CloudSQLInstanceInfo' = proto.Field( + proto.MESSAGE, + number=19, + oneof='step_info', + message='CloudSQLInstanceInfo', + ) + redis_instance: 'RedisInstanceInfo' = proto.Field( + proto.MESSAGE, + number=30, + oneof='step_info', + message='RedisInstanceInfo', + ) + redis_cluster: 'RedisClusterInfo' = proto.Field( + proto.MESSAGE, + number=31, + oneof='step_info', + message='RedisClusterInfo', + ) + cloud_function: 'CloudFunctionInfo' = proto.Field( + proto.MESSAGE, + number=20, + oneof='step_info', + message='CloudFunctionInfo', + ) + app_engine_version: 'AppEngineVersionInfo' = proto.Field( + proto.MESSAGE, + number=22, + oneof='step_info', + message='AppEngineVersionInfo', + ) + cloud_run_revision: 'CloudRunRevisionInfo' = proto.Field( + proto.MESSAGE, + number=23, + oneof='step_info', + message='CloudRunRevisionInfo', + ) + nat: 'NatInfo' = proto.Field( + proto.MESSAGE, + number=25, + oneof='step_info', + message='NatInfo', + ) + proxy_connection: 'ProxyConnectionInfo' = proto.Field( + proto.MESSAGE, + number=26, + oneof='step_info', + message='ProxyConnectionInfo', + ) + load_balancer_backend_info: 'LoadBalancerBackendInfo' = proto.Field( + proto.MESSAGE, + number=27, + oneof='step_info', + message='LoadBalancerBackendInfo', + ) + storage_bucket: 'StorageBucketInfo' = proto.Field( + proto.MESSAGE, + number=28, + oneof='step_info', + message='StorageBucketInfo', + ) + serverless_neg: 'ServerlessNegInfo' = proto.Field( + proto.MESSAGE, + number=29, + oneof='step_info', + message='ServerlessNegInfo', + ) + + +class InstanceInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + instance. + + Attributes: + display_name (str): + Name of a Compute Engine instance. + uri (str): + URI of a Compute Engine instance. + interface (str): + Name of the network interface of a Compute + Engine instance. + network_uri (str): + URI of a Compute Engine network. + internal_ip (str): + Internal IP address of the network interface. + external_ip (str): + External IP address of the network interface. + network_tags (MutableSequence[str]): + Network tags configured on the instance. + service_account (str): + Service account authorized for the instance. + psc_network_attachment_uri (str): + URI of the PSC network attachment the NIC is + attached to (if relevant). + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + interface: str = proto.Field( + proto.STRING, + number=3, + ) + network_uri: str = proto.Field( + proto.STRING, + number=4, + ) + internal_ip: str = proto.Field( + proto.STRING, + number=5, + ) + external_ip: str = proto.Field( + proto.STRING, + number=6, + ) + network_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + service_account: str = proto.Field( + proto.STRING, + number=8, + ) + psc_network_attachment_uri: str = proto.Field( + proto.STRING, + number=9, + ) + + +class NetworkInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + network. Next ID: 7 + + Attributes: + display_name (str): + Name of a Compute Engine network. + uri (str): + URI of a Compute Engine network. + matched_subnet_uri (str): + URI of the subnet matching the source IP + address of the test. + matched_ip_range (str): + The IP range of the subnet matching the + source IP address of the test. + region (str): + The region of the subnet matching the source + IP address of the test. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + matched_subnet_uri: str = proto.Field( + proto.STRING, + number=5, + ) + matched_ip_range: str = proto.Field( + proto.STRING, + number=4, + ) + region: str = proto.Field( + proto.STRING, + number=6, + ) + + +class FirewallInfo(proto.Message): + r"""For display only. Metadata associated with a VPC firewall + rule, an implied VPC firewall rule, or a firewall policy rule. + + Attributes: + display_name (str): + The display name of the firewall rule. This + field might be empty for firewall policy rules. + uri (str): + The URI of the firewall rule. This field is + not applicable to implied VPC firewall rules. + direction (str): + Possible values: INGRESS, EGRESS + action (str): + Possible values: ALLOW, DENY, APPLY_SECURITY_PROFILE_GROUP + priority (int): + The priority of the firewall rule. + network_uri (str): + The URI of the VPC network that the firewall + rule is associated with. This field is not + applicable to hierarchical firewall policy + rules. + target_tags (MutableSequence[str]): + The target tags defined by the VPC firewall + rule. This field is not applicable to firewall + policy rules. + target_service_accounts (MutableSequence[str]): + The target service accounts specified by the + firewall rule. + policy (str): + The name of the firewall policy that this + rule is associated with. This field is not + applicable to VPC firewall rules and implied VPC + firewall rules. + policy_uri (str): + The URI of the firewall policy that this rule + is associated with. This field is not applicable + to VPC firewall rules and implied VPC firewall + rules. + firewall_rule_type (google.cloud.network_management_v1.types.FirewallInfo.FirewallRuleType): + The firewall rule's type. + """ + class FirewallRuleType(proto.Enum): + r"""The firewall rule's type. + + Values: + FIREWALL_RULE_TYPE_UNSPECIFIED (0): + Unspecified type. + HIERARCHICAL_FIREWALL_POLICY_RULE (1): + Hierarchical firewall policy rule. For details, see + `Hierarchical firewall policies + overview `__. + VPC_FIREWALL_RULE (2): + VPC firewall rule. For details, see `VPC firewall rules + overview `__. + IMPLIED_VPC_FIREWALL_RULE (3): + Implied VPC firewall rule. For details, see `Implied + rules `__. + SERVERLESS_VPC_ACCESS_MANAGED_FIREWALL_RULE (4): + Implicit firewall rules that are managed by serverless VPC + access to allow ingress access. They are not visible in the + Google Cloud console. For details, see `VPC connector's + implicit + rules `__. + NETWORK_FIREWALL_POLICY_RULE (5): + Global network firewall policy rule. For details, see + `Network firewall + policies `__. + NETWORK_REGIONAL_FIREWALL_POLICY_RULE (6): + Regional network firewall policy rule. For details, see + `Regional network firewall + policies `__. + UNSUPPORTED_FIREWALL_POLICY_RULE (100): + Firewall policy rule containing attributes not yet supported + in Connectivity tests. Firewall analysis is skipped if such + a rule can potentially be matched. Please see the `list of + unsupported + configurations `__. + TRACKING_STATE (101): + Tracking state for response traffic created when request + traffic goes through allow firewall rule. For details, see + `firewall rules + specifications `__ + """ + FIREWALL_RULE_TYPE_UNSPECIFIED = 0 + HIERARCHICAL_FIREWALL_POLICY_RULE = 1 + VPC_FIREWALL_RULE = 2 + IMPLIED_VPC_FIREWALL_RULE = 3 + SERVERLESS_VPC_ACCESS_MANAGED_FIREWALL_RULE = 4 + NETWORK_FIREWALL_POLICY_RULE = 5 + NETWORK_REGIONAL_FIREWALL_POLICY_RULE = 6 + UNSUPPORTED_FIREWALL_POLICY_RULE = 100 + TRACKING_STATE = 101 + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + direction: str = proto.Field( + proto.STRING, + number=3, + ) + action: str = proto.Field( + proto.STRING, + number=4, + ) + priority: int = proto.Field( + proto.INT32, + number=5, + ) + network_uri: str = proto.Field( + proto.STRING, + number=6, + ) + target_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + target_service_accounts: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + policy: str = proto.Field( + proto.STRING, + number=9, + ) + policy_uri: str = proto.Field( + proto.STRING, + number=11, + ) + firewall_rule_type: FirewallRuleType = proto.Field( + proto.ENUM, + number=10, + enum=FirewallRuleType, + ) + + +class RouteInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + route. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + route_type (google.cloud.network_management_v1.types.RouteInfo.RouteType): + Type of route. + next_hop_type (google.cloud.network_management_v1.types.RouteInfo.NextHopType): + Type of next hop. + route_scope (google.cloud.network_management_v1.types.RouteInfo.RouteScope): + Indicates where route is applicable. + display_name (str): + Name of a route. + uri (str): + URI of a route (if applicable). + region (str): + Region of the route (if applicable). + dest_ip_range (str): + Destination IP range of the route. + next_hop (str): + Next hop of the route. + network_uri (str): + URI of a Compute Engine network. NETWORK + routes only. + priority (int): + Priority of the route. + instance_tags (MutableSequence[str]): + Instance tags of the route. + src_ip_range (str): + Source IP address range of the route. Policy + based routes only. + dest_port_ranges (MutableSequence[str]): + Destination port ranges of the route. Policy + based routes only. + src_port_ranges (MutableSequence[str]): + Source port ranges of the route. Policy based + routes only. + protocols (MutableSequence[str]): + Protocols of the route. Policy based routes + only. + ncc_hub_uri (str): + URI of a NCC Hub. NCC_HUB routes only. + + This field is a member of `oneof`_ ``_ncc_hub_uri``. + ncc_spoke_uri (str): + URI of a NCC Spoke. NCC_HUB routes only. + + This field is a member of `oneof`_ ``_ncc_spoke_uri``. + advertised_route_source_router_uri (str): + For advertised dynamic routes, the URI of the + Cloud Router that advertised the corresponding + IP prefix. + + This field is a member of `oneof`_ ``_advertised_route_source_router_uri``. + advertised_route_next_hop_uri (str): + For advertised routes, the URI of their next + hop, i.e. the URI of the hybrid endpoint (VPN + tunnel, Interconnect attachment, NCC router + appliance) the advertised prefix is advertised + through, or URI of the source peered network. + + This field is a member of `oneof`_ ``_advertised_route_next_hop_uri``. + """ + class RouteType(proto.Enum): + r"""Type of route: + + Values: + ROUTE_TYPE_UNSPECIFIED (0): + Unspecified type. Default value. + SUBNET (1): + Route is a subnet route automatically created + by the system. + STATIC (2): + Static route created by the user, including + the default route to the internet. + DYNAMIC (3): + Dynamic route exchanged between BGP peers. + PEERING_SUBNET (4): + A subnet route received from peering network. + PEERING_STATIC (5): + A static route received from peering network. + PEERING_DYNAMIC (6): + A dynamic route received from peering + network. + POLICY_BASED (7): + Policy based route. + ADVERTISED (101): + Advertised route. Synthetic route which is + used to transition from the + StartFromPrivateNetwork state in Connectivity + tests. + """ + ROUTE_TYPE_UNSPECIFIED = 0 + SUBNET = 1 + STATIC = 2 + DYNAMIC = 3 + PEERING_SUBNET = 4 + PEERING_STATIC = 5 + PEERING_DYNAMIC = 6 + POLICY_BASED = 7 + ADVERTISED = 101 + + class NextHopType(proto.Enum): + r"""Type of next hop: + + Values: + NEXT_HOP_TYPE_UNSPECIFIED (0): + Unspecified type. Default value. + NEXT_HOP_IP (1): + Next hop is an IP address. + NEXT_HOP_INSTANCE (2): + Next hop is a Compute Engine instance. + NEXT_HOP_NETWORK (3): + Next hop is a VPC network gateway. + NEXT_HOP_PEERING (4): + Next hop is a peering VPC. + NEXT_HOP_INTERCONNECT (5): + Next hop is an interconnect. + NEXT_HOP_VPN_TUNNEL (6): + Next hop is a VPN tunnel. + NEXT_HOP_VPN_GATEWAY (7): + Next hop is a VPN gateway. This scenario only + happens when tracing connectivity from an + on-premises network to Google Cloud through a + VPN. The analysis simulates a packet departing + from the on-premises network through a VPN + tunnel and arriving at a Cloud VPN gateway. + NEXT_HOP_INTERNET_GATEWAY (8): + Next hop is an internet gateway. + NEXT_HOP_BLACKHOLE (9): + Next hop is blackhole; that is, the next hop + either does not exist or is not running. + NEXT_HOP_ILB (10): + Next hop is the forwarding rule of an + Internal Load Balancer. + NEXT_HOP_ROUTER_APPLIANCE (11): + Next hop is a `router appliance + instance `__. + NEXT_HOP_NCC_HUB (12): + Next hop is an NCC hub. + """ + NEXT_HOP_TYPE_UNSPECIFIED = 0 + NEXT_HOP_IP = 1 + NEXT_HOP_INSTANCE = 2 + NEXT_HOP_NETWORK = 3 + NEXT_HOP_PEERING = 4 + NEXT_HOP_INTERCONNECT = 5 + NEXT_HOP_VPN_TUNNEL = 6 + NEXT_HOP_VPN_GATEWAY = 7 + NEXT_HOP_INTERNET_GATEWAY = 8 + NEXT_HOP_BLACKHOLE = 9 + NEXT_HOP_ILB = 10 + NEXT_HOP_ROUTER_APPLIANCE = 11 + NEXT_HOP_NCC_HUB = 12 + + class RouteScope(proto.Enum): + r"""Indicates where routes are applicable. + + Values: + ROUTE_SCOPE_UNSPECIFIED (0): + Unspecified scope. Default value. + NETWORK (1): + Route is applicable to packets in Network. + NCC_HUB (2): + Route is applicable to packets using NCC + Hub's routing table. + """ + ROUTE_SCOPE_UNSPECIFIED = 0 + NETWORK = 1 + NCC_HUB = 2 + + route_type: RouteType = proto.Field( + proto.ENUM, + number=8, + enum=RouteType, + ) + next_hop_type: NextHopType = proto.Field( + proto.ENUM, + number=9, + enum=NextHopType, + ) + route_scope: RouteScope = proto.Field( + proto.ENUM, + number=14, + enum=RouteScope, + ) + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + region: str = proto.Field( + proto.STRING, + number=19, + ) + dest_ip_range: str = proto.Field( + proto.STRING, + number=3, + ) + next_hop: str = proto.Field( + proto.STRING, + number=4, + ) + network_uri: str = proto.Field( + proto.STRING, + number=5, + ) + priority: int = proto.Field( + proto.INT32, + number=6, + ) + instance_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + src_ip_range: str = proto.Field( + proto.STRING, + number=10, + ) + dest_port_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=11, + ) + src_port_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=12, + ) + protocols: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=13, + ) + ncc_hub_uri: str = proto.Field( + proto.STRING, + number=15, + optional=True, + ) + ncc_spoke_uri: str = proto.Field( + proto.STRING, + number=16, + optional=True, + ) + advertised_route_source_router_uri: str = proto.Field( + proto.STRING, + number=17, + optional=True, + ) + advertised_route_next_hop_uri: str = proto.Field( + proto.STRING, + number=18, + optional=True, + ) + + +class GoogleServiceInfo(proto.Message): + r"""For display only. Details of a Google Service sending packets to a + VPC network. Although the source IP might be a publicly routable + address, some Google Services use special routes within Google + production infrastructure to reach Compute Engine Instances. + https://cloud.google.com/vpc/docs/routes#special_return_paths + + Attributes: + source_ip (str): + Source IP address. + google_service_type (google.cloud.network_management_v1.types.GoogleServiceInfo.GoogleServiceType): + Recognized type of a Google Service. + """ + class GoogleServiceType(proto.Enum): + r"""Recognized type of a Google Service. + + Values: + GOOGLE_SERVICE_TYPE_UNSPECIFIED (0): + Unspecified Google Service. + IAP (1): + Identity aware proxy. + https://cloud.google.com/iap/docs/using-tcp-forwarding + GFE_PROXY_OR_HEALTH_CHECK_PROBER (2): + One of two services sharing IP ranges: + + - Load Balancer proxy + - Centralized Health Check prober + https://cloud.google.com/load-balancing/docs/firewall-rules + CLOUD_DNS (3): + Connectivity from Cloud DNS to forwarding + targets or alternate name servers that use + private routing. + https://cloud.google.com/dns/docs/zones/forwarding-zones#firewall-rules + https://cloud.google.com/dns/docs/policies#firewall-rules + GOOGLE_API (4): + private.googleapis.com and + restricted.googleapis.com + GOOGLE_API_PSC (5): + Google API via Private Service Connect. + https://cloud.google.com/vpc/docs/configure-private-service-connect-apis + GOOGLE_API_VPC_SC (6): + Google API via VPC Service Controls. + https://cloud.google.com/vpc/docs/configure-private-service-connect-apis + """ + GOOGLE_SERVICE_TYPE_UNSPECIFIED = 0 + IAP = 1 + GFE_PROXY_OR_HEALTH_CHECK_PROBER = 2 + CLOUD_DNS = 3 + GOOGLE_API = 4 + GOOGLE_API_PSC = 5 + GOOGLE_API_VPC_SC = 6 + + source_ip: str = proto.Field( + proto.STRING, + number=1, + ) + google_service_type: GoogleServiceType = proto.Field( + proto.ENUM, + number=2, + enum=GoogleServiceType, + ) + + +class ForwardingRuleInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + forwarding rule. + + Attributes: + display_name (str): + Name of the forwarding rule. + uri (str): + URI of the forwarding rule. + matched_protocol (str): + Protocol defined in the forwarding rule that + matches the packet. + matched_port_range (str): + Port range defined in the forwarding rule + that matches the packet. + vip (str): + VIP of the forwarding rule. + target (str): + Target type of the forwarding rule. + network_uri (str): + Network URI. + region (str): + Region of the forwarding rule. Set only for + regional forwarding rules. + load_balancer_name (str): + Name of the load balancer the forwarding rule + belongs to. Empty for forwarding rules not + related to load balancers (like PSC forwarding + rules). + psc_service_attachment_uri (str): + URI of the PSC service attachment this + forwarding rule targets (if applicable). + psc_google_api_target (str): + PSC Google API target this forwarding rule + targets (if applicable). + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + matched_protocol: str = proto.Field( + proto.STRING, + number=3, + ) + matched_port_range: str = proto.Field( + proto.STRING, + number=6, + ) + vip: str = proto.Field( + proto.STRING, + number=4, + ) + target: str = proto.Field( + proto.STRING, + number=5, + ) + network_uri: str = proto.Field( + proto.STRING, + number=7, + ) + region: str = proto.Field( + proto.STRING, + number=8, + ) + load_balancer_name: str = proto.Field( + proto.STRING, + number=9, + ) + psc_service_attachment_uri: str = proto.Field( + proto.STRING, + number=10, + ) + psc_google_api_target: str = proto.Field( + proto.STRING, + number=11, + ) + + +class LoadBalancerInfo(proto.Message): + r"""For display only. Metadata associated with a load balancer. + + Attributes: + load_balancer_type (google.cloud.network_management_v1.types.LoadBalancerInfo.LoadBalancerType): + Type of the load balancer. + health_check_uri (str): + URI of the health check for the load + balancer. Deprecated and no longer populated as + different load balancer backends might have + different health checks. + backends (MutableSequence[google.cloud.network_management_v1.types.LoadBalancerBackend]): + Information for the loadbalancer backends. + backend_type (google.cloud.network_management_v1.types.LoadBalancerInfo.BackendType): + Type of load balancer's backend + configuration. + backend_uri (str): + Backend configuration URI. + """ + class LoadBalancerType(proto.Enum): + r"""The type definition for a load balancer: + + Values: + LOAD_BALANCER_TYPE_UNSPECIFIED (0): + Type is unspecified. + INTERNAL_TCP_UDP (1): + Internal TCP/UDP load balancer. + NETWORK_TCP_UDP (2): + Network TCP/UDP load balancer. + HTTP_PROXY (3): + HTTP(S) proxy load balancer. + TCP_PROXY (4): + TCP proxy load balancer. + SSL_PROXY (5): + SSL proxy load balancer. + """ + LOAD_BALANCER_TYPE_UNSPECIFIED = 0 + INTERNAL_TCP_UDP = 1 + NETWORK_TCP_UDP = 2 + HTTP_PROXY = 3 + TCP_PROXY = 4 + SSL_PROXY = 5 + + class BackendType(proto.Enum): + r"""The type definition for a load balancer backend + configuration: + + Values: + BACKEND_TYPE_UNSPECIFIED (0): + Type is unspecified. + BACKEND_SERVICE (1): + Backend Service as the load balancer's + backend. + TARGET_POOL (2): + Target Pool as the load balancer's backend. + TARGET_INSTANCE (3): + Target Instance as the load balancer's + backend. + """ + BACKEND_TYPE_UNSPECIFIED = 0 + BACKEND_SERVICE = 1 + TARGET_POOL = 2 + TARGET_INSTANCE = 3 + + load_balancer_type: LoadBalancerType = proto.Field( + proto.ENUM, + number=1, + enum=LoadBalancerType, + ) + health_check_uri: str = proto.Field( + proto.STRING, + number=2, + ) + backends: MutableSequence['LoadBalancerBackend'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LoadBalancerBackend', + ) + backend_type: BackendType = proto.Field( + proto.ENUM, + number=4, + enum=BackendType, + ) + backend_uri: str = proto.Field( + proto.STRING, + number=5, + ) + + +class LoadBalancerBackend(proto.Message): + r"""For display only. Metadata associated with a specific load + balancer backend. + + Attributes: + display_name (str): + Name of a Compute Engine instance or network + endpoint. + uri (str): + URI of a Compute Engine instance or network + endpoint. + health_check_firewall_state (google.cloud.network_management_v1.types.LoadBalancerBackend.HealthCheckFirewallState): + State of the health check firewall + configuration. + health_check_allowing_firewall_rules (MutableSequence[str]): + A list of firewall rule URIs allowing probes + from health check IP ranges. + health_check_blocking_firewall_rules (MutableSequence[str]): + A list of firewall rule URIs blocking probes + from health check IP ranges. + """ + class HealthCheckFirewallState(proto.Enum): + r"""State of a health check firewall configuration: + + Values: + HEALTH_CHECK_FIREWALL_STATE_UNSPECIFIED (0): + State is unspecified. Default state if not + populated. + CONFIGURED (1): + There are configured firewall rules to allow + health check probes to the backend. + MISCONFIGURED (2): + There are firewall rules configured to allow + partial health check ranges or block all health + check ranges. If a health check probe is sent + from denied IP ranges, the health check to the + backend will fail. Then, the backend will be + marked unhealthy and will not receive traffic + sent to the load balancer. + """ + HEALTH_CHECK_FIREWALL_STATE_UNSPECIFIED = 0 + CONFIGURED = 1 + MISCONFIGURED = 2 + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + health_check_firewall_state: HealthCheckFirewallState = proto.Field( + proto.ENUM, + number=3, + enum=HealthCheckFirewallState, + ) + health_check_allowing_firewall_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + health_check_blocking_firewall_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class VpnGatewayInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + VPN gateway. + + Attributes: + display_name (str): + Name of a VPN gateway. + uri (str): + URI of a VPN gateway. + network_uri (str): + URI of a Compute Engine network where the VPN + gateway is configured. + ip_address (str): + IP address of the VPN gateway. + vpn_tunnel_uri (str): + A VPN tunnel that is associated with this VPN + gateway. There may be multiple VPN tunnels + configured on a VPN gateway, and only the one + relevant to the test is displayed. + region (str): + Name of a Google Cloud region where this VPN + gateway is configured. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + network_uri: str = proto.Field( + proto.STRING, + number=3, + ) + ip_address: str = proto.Field( + proto.STRING, + number=4, + ) + vpn_tunnel_uri: str = proto.Field( + proto.STRING, + number=5, + ) + region: str = proto.Field( + proto.STRING, + number=6, + ) + + +class VpnTunnelInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + VPN tunnel. + + Attributes: + display_name (str): + Name of a VPN tunnel. + uri (str): + URI of a VPN tunnel. + source_gateway (str): + URI of the VPN gateway at local end of the + tunnel. + remote_gateway (str): + URI of a VPN gateway at remote end of the + tunnel. + remote_gateway_ip (str): + Remote VPN gateway's IP address. + source_gateway_ip (str): + Local VPN gateway's IP address. + network_uri (str): + URI of a Compute Engine network where the VPN + tunnel is configured. + region (str): + Name of a Google Cloud region where this VPN + tunnel is configured. + routing_type (google.cloud.network_management_v1.types.VpnTunnelInfo.RoutingType): + Type of the routing policy. + """ + class RoutingType(proto.Enum): + r"""Types of VPN routing policy. For details, refer to `Networks and + Tunnel + routing `__. + + Values: + ROUTING_TYPE_UNSPECIFIED (0): + Unspecified type. Default value. + ROUTE_BASED (1): + Route based VPN. + POLICY_BASED (2): + Policy based routing. + DYNAMIC (3): + Dynamic (BGP) routing. + """ + ROUTING_TYPE_UNSPECIFIED = 0 + ROUTE_BASED = 1 + POLICY_BASED = 2 + DYNAMIC = 3 + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + source_gateway: str = proto.Field( + proto.STRING, + number=3, + ) + remote_gateway: str = proto.Field( + proto.STRING, + number=4, + ) + remote_gateway_ip: str = proto.Field( + proto.STRING, + number=5, + ) + source_gateway_ip: str = proto.Field( + proto.STRING, + number=6, + ) + network_uri: str = proto.Field( + proto.STRING, + number=7, + ) + region: str = proto.Field( + proto.STRING, + number=8, + ) + routing_type: RoutingType = proto.Field( + proto.ENUM, + number=9, + enum=RoutingType, + ) + + +class EndpointInfo(proto.Message): + r"""For display only. The specification of the endpoints for the + test. EndpointInfo is derived from source and destination + Endpoint and validated by the backend data plane model. + + Attributes: + source_ip (str): + Source IP address. + destination_ip (str): + Destination IP address. + protocol (str): + IP protocol in string format, for example: + "TCP", "UDP", "ICMP". + source_port (int): + Source port. Only valid when protocol is TCP + or UDP. + destination_port (int): + Destination port. Only valid when protocol is + TCP or UDP. + source_network_uri (str): + URI of the network where this packet + originates from. + destination_network_uri (str): + URI of the network where this packet is sent + to. + source_agent_uri (str): + URI of the source telemetry agent this packet + originates from. + """ + + source_ip: str = proto.Field( + proto.STRING, + number=1, + ) + destination_ip: str = proto.Field( + proto.STRING, + number=2, + ) + protocol: str = proto.Field( + proto.STRING, + number=3, + ) + source_port: int = proto.Field( + proto.INT32, + number=4, + ) + destination_port: int = proto.Field( + proto.INT32, + number=5, + ) + source_network_uri: str = proto.Field( + proto.STRING, + number=6, + ) + destination_network_uri: str = proto.Field( + proto.STRING, + number=7, + ) + source_agent_uri: str = proto.Field( + proto.STRING, + number=8, + ) + + +class DeliverInfo(proto.Message): + r"""Details of the final state "deliver" and associated resource. + + Attributes: + target (google.cloud.network_management_v1.types.DeliverInfo.Target): + Target type where the packet is delivered to. + resource_uri (str): + URI of the resource that the packet is + delivered to. + ip_address (str): + IP address of the target (if applicable). + storage_bucket (str): + Name of the Cloud Storage Bucket the packet + is delivered to (if applicable). + psc_google_api_target (str): + PSC Google API target the packet is delivered + to (if applicable). + """ + class Target(proto.Enum): + r"""Deliver target types: + + Values: + TARGET_UNSPECIFIED (0): + Target not specified. + INSTANCE (1): + Target is a Compute Engine instance. + INTERNET (2): + Target is the internet. + GOOGLE_API (3): + Target is a Google API. + GKE_MASTER (4): + Target is a Google Kubernetes Engine cluster + master. + CLOUD_SQL_INSTANCE (5): + Target is a Cloud SQL instance. + PSC_PUBLISHED_SERVICE (6): + Target is a published service that uses `Private Service + Connect `__. + PSC_GOOGLE_API (7): + Target is Google APIs that use `Private Service + Connect `__. + PSC_VPC_SC (8): + Target is a VPC-SC that uses `Private Service + Connect `__. + SERVERLESS_NEG (9): + Target is a serverless network endpoint + group. + STORAGE_BUCKET (10): + Target is a Cloud Storage bucket. + PRIVATE_NETWORK (11): + Target is a private network. Used only for + return traces. + CLOUD_FUNCTION (12): + Target is a Cloud Function. Used only for + return traces. + APP_ENGINE_VERSION (13): + Target is a App Engine service version. Used + only for return traces. + CLOUD_RUN_REVISION (14): + Target is a Cloud Run revision. Used only for + return traces. + GOOGLE_MANAGED_SERVICE (15): + Target is a Google-managed service. Used only + for return traces. + REDIS_INSTANCE (16): + Target is a Redis Instance. + REDIS_CLUSTER (17): + Target is a Redis Cluster. + """ + TARGET_UNSPECIFIED = 0 + INSTANCE = 1 + INTERNET = 2 + GOOGLE_API = 3 + GKE_MASTER = 4 + CLOUD_SQL_INSTANCE = 5 + PSC_PUBLISHED_SERVICE = 6 + PSC_GOOGLE_API = 7 + PSC_VPC_SC = 8 + SERVERLESS_NEG = 9 + STORAGE_BUCKET = 10 + PRIVATE_NETWORK = 11 + CLOUD_FUNCTION = 12 + APP_ENGINE_VERSION = 13 + CLOUD_RUN_REVISION = 14 + GOOGLE_MANAGED_SERVICE = 15 + REDIS_INSTANCE = 16 + REDIS_CLUSTER = 17 + + target: Target = proto.Field( + proto.ENUM, + number=1, + enum=Target, + ) + resource_uri: str = proto.Field( + proto.STRING, + number=2, + ) + ip_address: str = proto.Field( + proto.STRING, + number=3, + ) + storage_bucket: str = proto.Field( + proto.STRING, + number=4, + ) + psc_google_api_target: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ForwardInfo(proto.Message): + r"""Details of the final state "forward" and associated resource. + + Attributes: + target (google.cloud.network_management_v1.types.ForwardInfo.Target): + Target type where this packet is forwarded + to. + resource_uri (str): + URI of the resource that the packet is + forwarded to. + ip_address (str): + IP address of the target (if applicable). + """ + class Target(proto.Enum): + r"""Forward target types. + + Values: + TARGET_UNSPECIFIED (0): + Target not specified. + PEERING_VPC (1): + Forwarded to a VPC peering network. + VPN_GATEWAY (2): + Forwarded to a Cloud VPN gateway. + INTERCONNECT (3): + Forwarded to a Cloud Interconnect connection. + GKE_MASTER (4): + Forwarded to a Google Kubernetes Engine + Container cluster master. + IMPORTED_CUSTOM_ROUTE_NEXT_HOP (5): + Forwarded to the next hop of a custom route + imported from a peering VPC. + CLOUD_SQL_INSTANCE (6): + Forwarded to a Cloud SQL instance. + ANOTHER_PROJECT (7): + Forwarded to a VPC network in another + project. + NCC_HUB (8): + Forwarded to an NCC Hub. + ROUTER_APPLIANCE (9): + Forwarded to a router appliance. + """ + TARGET_UNSPECIFIED = 0 + PEERING_VPC = 1 + VPN_GATEWAY = 2 + INTERCONNECT = 3 + GKE_MASTER = 4 + IMPORTED_CUSTOM_ROUTE_NEXT_HOP = 5 + CLOUD_SQL_INSTANCE = 6 + ANOTHER_PROJECT = 7 + NCC_HUB = 8 + ROUTER_APPLIANCE = 9 + + target: Target = proto.Field( + proto.ENUM, + number=1, + enum=Target, + ) + resource_uri: str = proto.Field( + proto.STRING, + number=2, + ) + ip_address: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AbortInfo(proto.Message): + r"""Details of the final state "abort" and associated resource. + + Attributes: + cause (google.cloud.network_management_v1.types.AbortInfo.Cause): + Causes that the analysis is aborted. + resource_uri (str): + URI of the resource that caused the abort. + ip_address (str): + IP address that caused the abort. + projects_missing_permission (MutableSequence[str]): + List of project IDs the user specified in the request but + lacks access to. In this case, analysis is aborted with the + PERMISSION_DENIED cause. + """ + class Cause(proto.Enum): + r"""Abort cause types: + + Values: + CAUSE_UNSPECIFIED (0): + Cause is unspecified. + UNKNOWN_NETWORK (1): + Aborted due to unknown network. Deprecated, + not used in the new tests. + UNKNOWN_PROJECT (3): + Aborted because no project information can be + derived from the test input. Deprecated, not + used in the new tests. + NO_EXTERNAL_IP (7): + Aborted because traffic is sent from a public + IP to an instance without an external IP. + Deprecated, not used in the new tests. + UNINTENDED_DESTINATION (8): + Aborted because none of the traces matches + destination information specified in the input + test request. Deprecated, not used in the new + tests. + SOURCE_ENDPOINT_NOT_FOUND (11): + Aborted because the source endpoint could not + be found. Deprecated, not used in the new tests. + MISMATCHED_SOURCE_NETWORK (12): + Aborted because the source network does not + match the source endpoint. Deprecated, not used + in the new tests. + DESTINATION_ENDPOINT_NOT_FOUND (13): + Aborted because the destination endpoint + could not be found. Deprecated, not used in the + new tests. + MISMATCHED_DESTINATION_NETWORK (14): + Aborted because the destination network does + not match the destination endpoint. Deprecated, + not used in the new tests. + UNKNOWN_IP (2): + Aborted because no endpoint with the packet's + destination IP address is found. + GOOGLE_MANAGED_SERVICE_UNKNOWN_IP (32): + Aborted because no endpoint with the packet's + destination IP is found in the Google-managed + project. + SOURCE_IP_ADDRESS_NOT_IN_SOURCE_NETWORK (23): + Aborted because the source IP address doesn't + belong to any of the subnets of the source VPC + network. + PERMISSION_DENIED (4): + Aborted because user lacks permission to + access all or part of the network configurations + required to run the test. + PERMISSION_DENIED_NO_CLOUD_NAT_CONFIGS (28): + Aborted because user lacks permission to + access Cloud NAT configs required to run the + test. + PERMISSION_DENIED_NO_NEG_ENDPOINT_CONFIGS (29): + Aborted because user lacks permission to + access Network endpoint group endpoint configs + required to run the test. + PERMISSION_DENIED_NO_CLOUD_ROUTER_CONFIGS (36): + Aborted because user lacks permission to + access Cloud Router configs required to run the + test. + NO_SOURCE_LOCATION (5): + Aborted because no valid source or + destination endpoint is derived from the input + test request. + INVALID_ARGUMENT (6): + Aborted because the source or destination + endpoint specified in the request is invalid. + Some examples: + + - The request might contain malformed resource + URI, project ID, or IP address. + - The request might contain inconsistent + information (for example, the request might + include both the instance and the network, but + the instance might not have a NIC in that + network). + TRACE_TOO_LONG (9): + Aborted because the number of steps in the + trace exceeds a certain limit. It might be + caused by a routing loop. + INTERNAL_ERROR (10): + Aborted due to internal server error. + UNSUPPORTED (15): + Aborted because the test scenario is not + supported. + MISMATCHED_IP_VERSION (16): + Aborted because the source and destination + resources have no common IP version. + GKE_KONNECTIVITY_PROXY_UNSUPPORTED (17): + Aborted because the connection between the + control plane and the node of the source cluster + is initiated by the node and managed by the + Konnectivity proxy. + RESOURCE_CONFIG_NOT_FOUND (18): + Aborted because expected resource + configuration was missing. + VM_INSTANCE_CONFIG_NOT_FOUND (24): + Aborted because expected VM instance + configuration was missing. + NETWORK_CONFIG_NOT_FOUND (25): + Aborted because expected network + configuration was missing. + FIREWALL_CONFIG_NOT_FOUND (26): + Aborted because expected firewall + configuration was missing. + ROUTE_CONFIG_NOT_FOUND (27): + Aborted because expected route configuration + was missing. + GOOGLE_MANAGED_SERVICE_AMBIGUOUS_PSC_ENDPOINT (19): + Aborted because a PSC endpoint selection for + the Google-managed service is ambiguous (several + PSC endpoints satisfy test input). + SOURCE_PSC_CLOUD_SQL_UNSUPPORTED (20): + Aborted because tests with a PSC-based Cloud + SQL instance as a source are not supported. + SOURCE_REDIS_CLUSTER_UNSUPPORTED (34): + Aborted because tests with a Redis Cluster as + a source are not supported. + SOURCE_REDIS_INSTANCE_UNSUPPORTED (35): + Aborted because tests with a Redis Instance + as a source are not supported. + SOURCE_FORWARDING_RULE_UNSUPPORTED (21): + Aborted because tests with a forwarding rule + as a source are not supported. + NON_ROUTABLE_IP_ADDRESS (22): + Aborted because one of the endpoints is a + non-routable IP address (loopback, link-local, + etc). + UNKNOWN_ISSUE_IN_GOOGLE_MANAGED_PROJECT (30): + Aborted due to an unknown issue in the + Google-managed project. + UNSUPPORTED_GOOGLE_MANAGED_PROJECT_CONFIG (31): + Aborted due to an unsupported configuration + of the Google-managed project. + """ + CAUSE_UNSPECIFIED = 0 + UNKNOWN_NETWORK = 1 + UNKNOWN_PROJECT = 3 + NO_EXTERNAL_IP = 7 + UNINTENDED_DESTINATION = 8 + SOURCE_ENDPOINT_NOT_FOUND = 11 + MISMATCHED_SOURCE_NETWORK = 12 + DESTINATION_ENDPOINT_NOT_FOUND = 13 + MISMATCHED_DESTINATION_NETWORK = 14 + UNKNOWN_IP = 2 + GOOGLE_MANAGED_SERVICE_UNKNOWN_IP = 32 + SOURCE_IP_ADDRESS_NOT_IN_SOURCE_NETWORK = 23 + PERMISSION_DENIED = 4 + PERMISSION_DENIED_NO_CLOUD_NAT_CONFIGS = 28 + PERMISSION_DENIED_NO_NEG_ENDPOINT_CONFIGS = 29 + PERMISSION_DENIED_NO_CLOUD_ROUTER_CONFIGS = 36 + NO_SOURCE_LOCATION = 5 + INVALID_ARGUMENT = 6 + TRACE_TOO_LONG = 9 + INTERNAL_ERROR = 10 + UNSUPPORTED = 15 + MISMATCHED_IP_VERSION = 16 + GKE_KONNECTIVITY_PROXY_UNSUPPORTED = 17 + RESOURCE_CONFIG_NOT_FOUND = 18 + VM_INSTANCE_CONFIG_NOT_FOUND = 24 + NETWORK_CONFIG_NOT_FOUND = 25 + FIREWALL_CONFIG_NOT_FOUND = 26 + ROUTE_CONFIG_NOT_FOUND = 27 + GOOGLE_MANAGED_SERVICE_AMBIGUOUS_PSC_ENDPOINT = 19 + SOURCE_PSC_CLOUD_SQL_UNSUPPORTED = 20 + SOURCE_REDIS_CLUSTER_UNSUPPORTED = 34 + SOURCE_REDIS_INSTANCE_UNSUPPORTED = 35 + SOURCE_FORWARDING_RULE_UNSUPPORTED = 21 + NON_ROUTABLE_IP_ADDRESS = 22 + UNKNOWN_ISSUE_IN_GOOGLE_MANAGED_PROJECT = 30 + UNSUPPORTED_GOOGLE_MANAGED_PROJECT_CONFIG = 31 + + cause: Cause = proto.Field( + proto.ENUM, + number=1, + enum=Cause, + ) + resource_uri: str = proto.Field( + proto.STRING, + number=2, + ) + ip_address: str = proto.Field( + proto.STRING, + number=4, + ) + projects_missing_permission: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DropInfo(proto.Message): + r"""Details of the final state "drop" and associated resource. + + Attributes: + cause (google.cloud.network_management_v1.types.DropInfo.Cause): + Cause that the packet is dropped. + resource_uri (str): + URI of the resource that caused the drop. + source_ip (str): + Source IP address of the dropped packet (if + relevant). + destination_ip (str): + Destination IP address of the dropped packet + (if relevant). + region (str): + Region of the dropped packet (if relevant). + """ + class Cause(proto.Enum): + r"""Drop cause types: + + Values: + CAUSE_UNSPECIFIED (0): + Cause is unspecified. + UNKNOWN_EXTERNAL_ADDRESS (1): + Destination external address cannot be + resolved to a known target. If the address is + used in a Google Cloud project, provide the + project ID as test input. + FOREIGN_IP_DISALLOWED (2): + A Compute Engine instance can only send or receive a packet + with a foreign IP address if ip_forward is enabled. + FIREWALL_RULE (3): + Dropped due to a firewall rule, unless + allowed due to connection tracking. + NO_ROUTE (4): + Dropped due to no matching routes. + ROUTE_BLACKHOLE (5): + Dropped due to invalid route. Route's next + hop is a blackhole. + ROUTE_WRONG_NETWORK (6): + Packet is sent to a wrong (unintended) + network. Example: you trace a packet from + VM1:Network1 to VM2:Network2, however, the route + configured in Network1 sends the packet destined + for VM2's IP address to Network3. + ROUTE_NEXT_HOP_IP_ADDRESS_NOT_RESOLVED (42): + Route's next hop IP address cannot be + resolved to a GCP resource. + ROUTE_NEXT_HOP_RESOURCE_NOT_FOUND (43): + Route's next hop resource is not found. + ROUTE_NEXT_HOP_INSTANCE_WRONG_NETWORK (49): + Route's next hop instance doesn't have a NIC + in the route's network. + ROUTE_NEXT_HOP_INSTANCE_NON_PRIMARY_IP (50): + Route's next hop IP address is not a primary + IP address of the next hop instance. + ROUTE_NEXT_HOP_FORWARDING_RULE_IP_MISMATCH (51): + Route's next hop forwarding rule doesn't + match next hop IP address. + ROUTE_NEXT_HOP_VPN_TUNNEL_NOT_ESTABLISHED (52): + Route's next hop VPN tunnel is down (does not + have valid IKE SAs). + ROUTE_NEXT_HOP_FORWARDING_RULE_TYPE_INVALID (53): + Route's next hop forwarding rule type is + invalid (it's not a forwarding rule of the + internal passthrough load balancer). + NO_ROUTE_FROM_INTERNET_TO_PRIVATE_IPV6_ADDRESS (44): + Packet is sent from the Internet to the + private IPv6 address. + VPN_TUNNEL_LOCAL_SELECTOR_MISMATCH (45): + The packet does not match a policy-based VPN + tunnel local selector. + VPN_TUNNEL_REMOTE_SELECTOR_MISMATCH (46): + The packet does not match a policy-based VPN + tunnel remote selector. + PRIVATE_TRAFFIC_TO_INTERNET (7): + Packet with internal destination address sent + to the internet gateway. + PRIVATE_GOOGLE_ACCESS_DISALLOWED (8): + Instance with only an internal IP address + tries to access Google API and services, but + private Google access is not enabled in the + subnet. + PRIVATE_GOOGLE_ACCESS_VIA_VPN_TUNNEL_UNSUPPORTED (47): + Source endpoint tries to access Google API + and services through the VPN tunnel to another + network, but Private Google Access needs to be + enabled in the source endpoint network. + NO_EXTERNAL_ADDRESS (9): + Instance with only an internal IP address + tries to access external hosts, but Cloud NAT is + not enabled in the subnet, unless special + configurations on a VM allow this connection. + UNKNOWN_INTERNAL_ADDRESS (10): + Destination internal address cannot be + resolved to a known target. If this is a shared + VPC scenario, verify if the service project ID + is provided as test input. Otherwise, verify if + the IP address is being used in the project. + FORWARDING_RULE_MISMATCH (11): + Forwarding rule's protocol and ports do not + match the packet header. + FORWARDING_RULE_NO_INSTANCES (12): + Forwarding rule does not have backends + configured. + FIREWALL_BLOCKING_LOAD_BALANCER_BACKEND_HEALTH_CHECK (13): + Firewalls block the health check probes to the backends and + cause the backends to be unavailable for traffic from the + load balancer. For more details, see `Health check firewall + rules `__. + INSTANCE_NOT_RUNNING (14): + Packet is sent from or to a Compute Engine + instance that is not in a running state. + GKE_CLUSTER_NOT_RUNNING (27): + Packet sent from or to a GKE cluster that is + not in running state. + CLOUD_SQL_INSTANCE_NOT_RUNNING (28): + Packet sent from or to a Cloud SQL instance + that is not in running state. + REDIS_INSTANCE_NOT_RUNNING (68): + Packet sent from or to a Redis Instance that + is not in running state. + REDIS_CLUSTER_NOT_RUNNING (69): + Packet sent from or to a Redis Cluster that + is not in running state. + TRAFFIC_TYPE_BLOCKED (15): + The type of traffic is blocked and the user cannot configure + a firewall rule to enable it. See `Always blocked + traffic `__ + for more details. + GKE_MASTER_UNAUTHORIZED_ACCESS (16): + Access to Google Kubernetes Engine cluster master's endpoint + is not authorized. See `Access to the cluster + endpoints `__ + for more details. + CLOUD_SQL_INSTANCE_UNAUTHORIZED_ACCESS (17): + Access to the Cloud SQL instance endpoint is not authorized. + See `Authorizing with authorized + networks `__ + for more details. + DROPPED_INSIDE_GKE_SERVICE (18): + Packet was dropped inside Google Kubernetes + Engine Service. + DROPPED_INSIDE_CLOUD_SQL_SERVICE (19): + Packet was dropped inside Cloud SQL Service. + GOOGLE_MANAGED_SERVICE_NO_PEERING (20): + Packet was dropped because there is no + peering between the originating network and the + Google Managed Services Network. + GOOGLE_MANAGED_SERVICE_NO_PSC_ENDPOINT (38): + Packet was dropped because the Google-managed + service uses Private Service Connect (PSC), but + the PSC endpoint is not found in the project. + GKE_PSC_ENDPOINT_MISSING (36): + Packet was dropped because the GKE cluster + uses Private Service Connect (PSC), but the PSC + endpoint is not found in the project. + CLOUD_SQL_INSTANCE_NO_IP_ADDRESS (21): + Packet was dropped because the Cloud SQL + instance has neither a private nor a public IP + address. + GKE_CONTROL_PLANE_REGION_MISMATCH (30): + Packet was dropped because a GKE cluster + private endpoint is unreachable from a region + different from the cluster's region. + PUBLIC_GKE_CONTROL_PLANE_TO_PRIVATE_DESTINATION (31): + Packet sent from a public GKE cluster control + plane to a private IP address. + GKE_CONTROL_PLANE_NO_ROUTE (32): + Packet was dropped because there is no route + from a GKE cluster control plane to a + destination network. + CLOUD_SQL_INSTANCE_NOT_CONFIGURED_FOR_EXTERNAL_TRAFFIC (33): + Packet sent from a Cloud SQL instance to an + external IP address is not allowed. The Cloud + SQL instance is not configured to send packets + to external IP addresses. + PUBLIC_CLOUD_SQL_INSTANCE_TO_PRIVATE_DESTINATION (34): + Packet sent from a Cloud SQL instance with + only a public IP address to a private IP + address. + CLOUD_SQL_INSTANCE_NO_ROUTE (35): + Packet was dropped because there is no route + from a Cloud SQL instance to a destination + network. + CLOUD_SQL_CONNECTOR_REQUIRED (63): + Packet was dropped because the Cloud SQL + instance requires all connections to use Cloud + SQL connectors and to target the Cloud SQL proxy + port (3307). + CLOUD_FUNCTION_NOT_ACTIVE (22): + Packet could be dropped because the Cloud + Function is not in an active status. + VPC_CONNECTOR_NOT_SET (23): + Packet could be dropped because no VPC + connector is set. + VPC_CONNECTOR_NOT_RUNNING (24): + Packet could be dropped because the VPC + connector is not in a running state. + VPC_CONNECTOR_SERVERLESS_TRAFFIC_BLOCKED (60): + Packet could be dropped because the traffic + from the serverless service to the VPC connector + is not allowed. + VPC_CONNECTOR_HEALTH_CHECK_TRAFFIC_BLOCKED (61): + Packet could be dropped because the health + check traffic to the VPC connector is not + allowed. + FORWARDING_RULE_REGION_MISMATCH (25): + Packet could be dropped because it was sent + from a different region to a regional forwarding + without global access. + PSC_CONNECTION_NOT_ACCEPTED (26): + The Private Service Connect endpoint is in a + project that is not approved to connect to the + service. + PSC_ENDPOINT_ACCESSED_FROM_PEERED_NETWORK (41): + The packet is sent to the Private Service Connect endpoint + over the peering, but `it's not + supported `__. + PSC_NEG_PRODUCER_ENDPOINT_NO_GLOBAL_ACCESS (48): + The packet is sent to the Private Service + Connect backend (network endpoint group), but + the producer PSC forwarding rule does not have + global access enabled. + PSC_NEG_PRODUCER_FORWARDING_RULE_MULTIPLE_PORTS (54): + The packet is sent to the Private Service + Connect backend (network endpoint group), but + the producer PSC forwarding rule has multiple + ports specified. + CLOUD_SQL_PSC_NEG_UNSUPPORTED (58): + The packet is sent to the Private Service + Connect backend (network endpoint group) + targeting a Cloud SQL service attachment, but + this configuration is not supported. + NO_NAT_SUBNETS_FOR_PSC_SERVICE_ATTACHMENT (57): + No NAT subnets are defined for the PSC + service attachment. + PSC_TRANSITIVITY_NOT_PROPAGATED (64): + PSC endpoint is accessed via NCC, but PSC + transitivity configuration is not yet + propagated. + HYBRID_NEG_NON_DYNAMIC_ROUTE_MATCHED (55): + The packet sent from the hybrid NEG proxy + matches a non-dynamic route, but such a + configuration is not supported. + HYBRID_NEG_NON_LOCAL_DYNAMIC_ROUTE_MATCHED (56): + The packet sent from the hybrid NEG proxy + matches a dynamic route with a next hop in a + different region, but such a configuration is + not supported. + CLOUD_RUN_REVISION_NOT_READY (29): + Packet sent from a Cloud Run revision that is + not ready. + DROPPED_INSIDE_PSC_SERVICE_PRODUCER (37): + Packet was dropped inside Private Service + Connect service producer. + LOAD_BALANCER_HAS_NO_PROXY_SUBNET (39): + Packet sent to a load balancer, which + requires a proxy-only subnet and the subnet is + not found. + CLOUD_NAT_NO_ADDRESSES (40): + Packet sent to Cloud Nat without active NAT + IPs. + ROUTING_LOOP (59): + Packet is stuck in a routing loop. + DROPPED_INSIDE_GOOGLE_MANAGED_SERVICE (62): + Packet is dropped inside a Google-managed + service due to being delivered in return trace + to an endpoint that doesn't match the endpoint + the packet was sent from in forward trace. Used + only for return traces. + LOAD_BALANCER_BACKEND_INVALID_NETWORK (65): + Packet is dropped due to a load balancer + backend instance not having a network interface + in the network expected by the load balancer. + BACKEND_SERVICE_NAMED_PORT_NOT_DEFINED (66): + Packet is dropped due to a backend service + named port not being defined on the instance + group level. + DESTINATION_IS_PRIVATE_NAT_IP_RANGE (67): + Packet is dropped due to a destination IP + range being part of a Private NAT IP range. + DROPPED_INSIDE_REDIS_INSTANCE_SERVICE (70): + Generic drop cause for a packet being dropped + inside a Redis Instance service project. + REDIS_INSTANCE_UNSUPPORTED_PORT (71): + Packet is dropped due to an unsupported port + being used to connect to a Redis Instance. Port + 6379 should be used to connect to a Redis + Instance. + REDIS_INSTANCE_CONNECTING_FROM_PUPI_ADDRESS (72): + Packet is dropped due to connecting from PUPI + address to a PSA based Redis Instance. + REDIS_INSTANCE_NO_ROUTE_TO_DESTINATION_NETWORK (73): + Packet is dropped due to no route to the + destination network. + REDIS_INSTANCE_NO_EXTERNAL_IP (74): + Redis Instance does not have an external IP + address. + REDIS_INSTANCE_UNSUPPORTED_PROTOCOL (78): + Packet is dropped due to an unsupported + protocol being used to connect to a Redis + Instance. Only TCP connections are accepted by a + Redis Instance. + DROPPED_INSIDE_REDIS_CLUSTER_SERVICE (75): + Generic drop cause for a packet being dropped + inside a Redis Cluster service project. + REDIS_CLUSTER_UNSUPPORTED_PORT (76): + Packet is dropped due to an unsupported port + being used to connect to a Redis Cluster. Ports + 6379 and 11000 to 13047 should be used to + connect to a Redis Cluster. + REDIS_CLUSTER_NO_EXTERNAL_IP (77): + Redis Cluster does not have an external IP + address. + REDIS_CLUSTER_UNSUPPORTED_PROTOCOL (79): + Packet is dropped due to an unsupported + protocol being used to connect to a Redis + Cluster. Only TCP connections are accepted by a + Redis Cluster. + NO_ADVERTISED_ROUTE_TO_GCP_DESTINATION (80): + Packet from the non-GCP (on-prem) or unknown + GCP network is dropped due to the destination IP + address not belonging to any IP prefix + advertised via BGP by the Cloud Router. + NO_TRAFFIC_SELECTOR_TO_GCP_DESTINATION (81): + Packet from the non-GCP (on-prem) or unknown + GCP network is dropped due to the destination IP + address not belonging to any IP prefix included + to the local traffic selector of the VPN tunnel. + NO_KNOWN_ROUTE_FROM_PEERED_NETWORK_TO_DESTINATION (82): + Packet from the unknown peered network is + dropped due to no known route from the source + network to the destination IP address. + PRIVATE_NAT_TO_PSC_ENDPOINT_UNSUPPORTED (83): + Sending packets processed by the Private NAT + Gateways to the Private Service Connect + endpoints is not supported. + """ + CAUSE_UNSPECIFIED = 0 + UNKNOWN_EXTERNAL_ADDRESS = 1 + FOREIGN_IP_DISALLOWED = 2 + FIREWALL_RULE = 3 + NO_ROUTE = 4 + ROUTE_BLACKHOLE = 5 + ROUTE_WRONG_NETWORK = 6 + ROUTE_NEXT_HOP_IP_ADDRESS_NOT_RESOLVED = 42 + ROUTE_NEXT_HOP_RESOURCE_NOT_FOUND = 43 + ROUTE_NEXT_HOP_INSTANCE_WRONG_NETWORK = 49 + ROUTE_NEXT_HOP_INSTANCE_NON_PRIMARY_IP = 50 + ROUTE_NEXT_HOP_FORWARDING_RULE_IP_MISMATCH = 51 + ROUTE_NEXT_HOP_VPN_TUNNEL_NOT_ESTABLISHED = 52 + ROUTE_NEXT_HOP_FORWARDING_RULE_TYPE_INVALID = 53 + NO_ROUTE_FROM_INTERNET_TO_PRIVATE_IPV6_ADDRESS = 44 + VPN_TUNNEL_LOCAL_SELECTOR_MISMATCH = 45 + VPN_TUNNEL_REMOTE_SELECTOR_MISMATCH = 46 + PRIVATE_TRAFFIC_TO_INTERNET = 7 + PRIVATE_GOOGLE_ACCESS_DISALLOWED = 8 + PRIVATE_GOOGLE_ACCESS_VIA_VPN_TUNNEL_UNSUPPORTED = 47 + NO_EXTERNAL_ADDRESS = 9 + UNKNOWN_INTERNAL_ADDRESS = 10 + FORWARDING_RULE_MISMATCH = 11 + FORWARDING_RULE_NO_INSTANCES = 12 + FIREWALL_BLOCKING_LOAD_BALANCER_BACKEND_HEALTH_CHECK = 13 + INSTANCE_NOT_RUNNING = 14 + GKE_CLUSTER_NOT_RUNNING = 27 + CLOUD_SQL_INSTANCE_NOT_RUNNING = 28 + REDIS_INSTANCE_NOT_RUNNING = 68 + REDIS_CLUSTER_NOT_RUNNING = 69 + TRAFFIC_TYPE_BLOCKED = 15 + GKE_MASTER_UNAUTHORIZED_ACCESS = 16 + CLOUD_SQL_INSTANCE_UNAUTHORIZED_ACCESS = 17 + DROPPED_INSIDE_GKE_SERVICE = 18 + DROPPED_INSIDE_CLOUD_SQL_SERVICE = 19 + GOOGLE_MANAGED_SERVICE_NO_PEERING = 20 + GOOGLE_MANAGED_SERVICE_NO_PSC_ENDPOINT = 38 + GKE_PSC_ENDPOINT_MISSING = 36 + CLOUD_SQL_INSTANCE_NO_IP_ADDRESS = 21 + GKE_CONTROL_PLANE_REGION_MISMATCH = 30 + PUBLIC_GKE_CONTROL_PLANE_TO_PRIVATE_DESTINATION = 31 + GKE_CONTROL_PLANE_NO_ROUTE = 32 + CLOUD_SQL_INSTANCE_NOT_CONFIGURED_FOR_EXTERNAL_TRAFFIC = 33 + PUBLIC_CLOUD_SQL_INSTANCE_TO_PRIVATE_DESTINATION = 34 + CLOUD_SQL_INSTANCE_NO_ROUTE = 35 + CLOUD_SQL_CONNECTOR_REQUIRED = 63 + CLOUD_FUNCTION_NOT_ACTIVE = 22 + VPC_CONNECTOR_NOT_SET = 23 + VPC_CONNECTOR_NOT_RUNNING = 24 + VPC_CONNECTOR_SERVERLESS_TRAFFIC_BLOCKED = 60 + VPC_CONNECTOR_HEALTH_CHECK_TRAFFIC_BLOCKED = 61 + FORWARDING_RULE_REGION_MISMATCH = 25 + PSC_CONNECTION_NOT_ACCEPTED = 26 + PSC_ENDPOINT_ACCESSED_FROM_PEERED_NETWORK = 41 + PSC_NEG_PRODUCER_ENDPOINT_NO_GLOBAL_ACCESS = 48 + PSC_NEG_PRODUCER_FORWARDING_RULE_MULTIPLE_PORTS = 54 + CLOUD_SQL_PSC_NEG_UNSUPPORTED = 58 + NO_NAT_SUBNETS_FOR_PSC_SERVICE_ATTACHMENT = 57 + PSC_TRANSITIVITY_NOT_PROPAGATED = 64 + HYBRID_NEG_NON_DYNAMIC_ROUTE_MATCHED = 55 + HYBRID_NEG_NON_LOCAL_DYNAMIC_ROUTE_MATCHED = 56 + CLOUD_RUN_REVISION_NOT_READY = 29 + DROPPED_INSIDE_PSC_SERVICE_PRODUCER = 37 + LOAD_BALANCER_HAS_NO_PROXY_SUBNET = 39 + CLOUD_NAT_NO_ADDRESSES = 40 + ROUTING_LOOP = 59 + DROPPED_INSIDE_GOOGLE_MANAGED_SERVICE = 62 + LOAD_BALANCER_BACKEND_INVALID_NETWORK = 65 + BACKEND_SERVICE_NAMED_PORT_NOT_DEFINED = 66 + DESTINATION_IS_PRIVATE_NAT_IP_RANGE = 67 + DROPPED_INSIDE_REDIS_INSTANCE_SERVICE = 70 + REDIS_INSTANCE_UNSUPPORTED_PORT = 71 + REDIS_INSTANCE_CONNECTING_FROM_PUPI_ADDRESS = 72 + REDIS_INSTANCE_NO_ROUTE_TO_DESTINATION_NETWORK = 73 + REDIS_INSTANCE_NO_EXTERNAL_IP = 74 + REDIS_INSTANCE_UNSUPPORTED_PROTOCOL = 78 + DROPPED_INSIDE_REDIS_CLUSTER_SERVICE = 75 + REDIS_CLUSTER_UNSUPPORTED_PORT = 76 + REDIS_CLUSTER_NO_EXTERNAL_IP = 77 + REDIS_CLUSTER_UNSUPPORTED_PROTOCOL = 79 + NO_ADVERTISED_ROUTE_TO_GCP_DESTINATION = 80 + NO_TRAFFIC_SELECTOR_TO_GCP_DESTINATION = 81 + NO_KNOWN_ROUTE_FROM_PEERED_NETWORK_TO_DESTINATION = 82 + PRIVATE_NAT_TO_PSC_ENDPOINT_UNSUPPORTED = 83 + + cause: Cause = proto.Field( + proto.ENUM, + number=1, + enum=Cause, + ) + resource_uri: str = proto.Field( + proto.STRING, + number=2, + ) + source_ip: str = proto.Field( + proto.STRING, + number=3, + ) + destination_ip: str = proto.Field( + proto.STRING, + number=4, + ) + region: str = proto.Field( + proto.STRING, + number=5, + ) + + +class GKEMasterInfo(proto.Message): + r"""For display only. Metadata associated with a Google + Kubernetes Engine (GKE) cluster master. + + Attributes: + cluster_uri (str): + URI of a GKE cluster. + cluster_network_uri (str): + URI of a GKE cluster network. + internal_ip (str): + Internal IP address of a GKE cluster control + plane. + external_ip (str): + External IP address of a GKE cluster control + plane. + dns_endpoint (str): + DNS endpoint of a GKE cluster control plane. + """ + + cluster_uri: str = proto.Field( + proto.STRING, + number=2, + ) + cluster_network_uri: str = proto.Field( + proto.STRING, + number=4, + ) + internal_ip: str = proto.Field( + proto.STRING, + number=5, + ) + external_ip: str = proto.Field( + proto.STRING, + number=6, + ) + dns_endpoint: str = proto.Field( + proto.STRING, + number=7, + ) + + +class CloudSQLInstanceInfo(proto.Message): + r"""For display only. Metadata associated with a Cloud SQL + instance. + + Attributes: + display_name (str): + Name of a Cloud SQL instance. + uri (str): + URI of a Cloud SQL instance. + network_uri (str): + URI of a Cloud SQL instance network or empty + string if the instance does not have one. + internal_ip (str): + Internal IP address of a Cloud SQL instance. + external_ip (str): + External IP address of a Cloud SQL instance. + region (str): + Region in which the Cloud SQL instance is + running. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + network_uri: str = proto.Field( + proto.STRING, + number=4, + ) + internal_ip: str = proto.Field( + proto.STRING, + number=5, + ) + external_ip: str = proto.Field( + proto.STRING, + number=6, + ) + region: str = proto.Field( + proto.STRING, + number=7, + ) + + +class RedisInstanceInfo(proto.Message): + r"""For display only. Metadata associated with a Cloud Redis + Instance. + + Attributes: + display_name (str): + Name of a Cloud Redis Instance. + uri (str): + URI of a Cloud Redis Instance. + network_uri (str): + URI of a Cloud Redis Instance network. + primary_endpoint_ip (str): + Primary endpoint IP address of a Cloud Redis + Instance. + read_endpoint_ip (str): + Read endpoint IP address of a Cloud Redis + Instance (if applicable). + region (str): + Region in which the Cloud Redis Instance is + defined. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + network_uri: str = proto.Field( + proto.STRING, + number=3, + ) + primary_endpoint_ip: str = proto.Field( + proto.STRING, + number=4, + ) + read_endpoint_ip: str = proto.Field( + proto.STRING, + number=5, + ) + region: str = proto.Field( + proto.STRING, + number=6, + ) + + +class RedisClusterInfo(proto.Message): + r"""For display only. Metadata associated with a Redis Cluster. + + Attributes: + display_name (str): + Name of a Redis Cluster. + uri (str): + URI of a Redis Cluster in format + "projects/{project_id}/locations/{location}/clusters/{cluster_id}". + network_uri (str): + URI of a Redis Cluster network in format + "projects/{project_id}/global/networks/{network_id}". + discovery_endpoint_ip_address (str): + Discovery endpoint IP address of a Redis + Cluster. + secondary_endpoint_ip_address (str): + Secondary endpoint IP address of a Redis + Cluster. + location (str): + Name of the region in which the Redis Cluster + is defined. For example, "us-central1". + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + network_uri: str = proto.Field( + proto.STRING, + number=3, + ) + discovery_endpoint_ip_address: str = proto.Field( + proto.STRING, + number=4, + ) + secondary_endpoint_ip_address: str = proto.Field( + proto.STRING, + number=5, + ) + location: str = proto.Field( + proto.STRING, + number=6, + ) + + +class CloudFunctionInfo(proto.Message): + r"""For display only. Metadata associated with a Cloud Function. + + Attributes: + display_name (str): + Name of a Cloud Function. + uri (str): + URI of a Cloud Function. + location (str): + Location in which the Cloud Function is + deployed. + version_id (int): + Latest successfully deployed version id of + the Cloud Function. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + location: str = proto.Field( + proto.STRING, + number=3, + ) + version_id: int = proto.Field( + proto.INT64, + number=4, + ) + + +class CloudRunRevisionInfo(proto.Message): + r"""For display only. Metadata associated with a Cloud Run + revision. + + Attributes: + display_name (str): + Name of a Cloud Run revision. + uri (str): + URI of a Cloud Run revision. + location (str): + Location in which this revision is deployed. + service_uri (str): + URI of Cloud Run service this revision + belongs to. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + location: str = proto.Field( + proto.STRING, + number=4, + ) + service_uri: str = proto.Field( + proto.STRING, + number=5, + ) + + +class AppEngineVersionInfo(proto.Message): + r"""For display only. Metadata associated with an App Engine + version. + + Attributes: + display_name (str): + Name of an App Engine version. + uri (str): + URI of an App Engine version. + runtime (str): + Runtime of the App Engine version. + environment (str): + App Engine execution environment for a + version. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + runtime: str = proto.Field( + proto.STRING, + number=3, + ) + environment: str = proto.Field( + proto.STRING, + number=4, + ) + + +class VpcConnectorInfo(proto.Message): + r"""For display only. Metadata associated with a VPC connector. + + Attributes: + display_name (str): + Name of a VPC connector. + uri (str): + URI of a VPC connector. + location (str): + Location in which the VPC connector is + deployed. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + location: str = proto.Field( + proto.STRING, + number=3, + ) + + +class NatInfo(proto.Message): + r"""For display only. Metadata associated with NAT. + + Attributes: + type_ (google.cloud.network_management_v1.types.NatInfo.Type): + Type of NAT. + protocol (str): + IP protocol in string format, for example: + "TCP", "UDP", "ICMP". + network_uri (str): + URI of the network where NAT translation + takes place. + old_source_ip (str): + Source IP address before NAT translation. + new_source_ip (str): + Source IP address after NAT translation. + old_destination_ip (str): + Destination IP address before NAT + translation. + new_destination_ip (str): + Destination IP address after NAT translation. + old_source_port (int): + Source port before NAT translation. Only + valid when protocol is TCP or UDP. + new_source_port (int): + Source port after NAT translation. Only valid + when protocol is TCP or UDP. + old_destination_port (int): + Destination port before NAT translation. Only + valid when protocol is TCP or UDP. + new_destination_port (int): + Destination port after NAT translation. Only + valid when protocol is TCP or UDP. + router_uri (str): + Uri of the Cloud Router. Only valid when type is CLOUD_NAT. + nat_gateway_name (str): + The name of Cloud NAT Gateway. Only valid when type is + CLOUD_NAT. + """ + class Type(proto.Enum): + r"""Types of NAT. + + Values: + TYPE_UNSPECIFIED (0): + Type is unspecified. + INTERNAL_TO_EXTERNAL (1): + From Compute Engine instance's internal + address to external address. + EXTERNAL_TO_INTERNAL (2): + From Compute Engine instance's external + address to internal address. + CLOUD_NAT (3): + Cloud NAT Gateway. + PRIVATE_SERVICE_CONNECT (4): + Private service connect NAT. + """ + TYPE_UNSPECIFIED = 0 + INTERNAL_TO_EXTERNAL = 1 + EXTERNAL_TO_INTERNAL = 2 + CLOUD_NAT = 3 + PRIVATE_SERVICE_CONNECT = 4 + + type_: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + protocol: str = proto.Field( + proto.STRING, + number=2, + ) + network_uri: str = proto.Field( + proto.STRING, + number=3, + ) + old_source_ip: str = proto.Field( + proto.STRING, + number=4, + ) + new_source_ip: str = proto.Field( + proto.STRING, + number=5, + ) + old_destination_ip: str = proto.Field( + proto.STRING, + number=6, + ) + new_destination_ip: str = proto.Field( + proto.STRING, + number=7, + ) + old_source_port: int = proto.Field( + proto.INT32, + number=8, + ) + new_source_port: int = proto.Field( + proto.INT32, + number=9, + ) + old_destination_port: int = proto.Field( + proto.INT32, + number=10, + ) + new_destination_port: int = proto.Field( + proto.INT32, + number=11, + ) + router_uri: str = proto.Field( + proto.STRING, + number=12, + ) + nat_gateway_name: str = proto.Field( + proto.STRING, + number=13, + ) + + +class ProxyConnectionInfo(proto.Message): + r"""For display only. Metadata associated with ProxyConnection. + + Attributes: + protocol (str): + IP protocol in string format, for example: + "TCP", "UDP", "ICMP". + old_source_ip (str): + Source IP address of an original connection. + new_source_ip (str): + Source IP address of a new connection. + old_destination_ip (str): + Destination IP address of an original + connection + new_destination_ip (str): + Destination IP address of a new connection. + old_source_port (int): + Source port of an original connection. Only + valid when protocol is TCP or UDP. + new_source_port (int): + Source port of a new connection. Only valid + when protocol is TCP or UDP. + old_destination_port (int): + Destination port of an original connection. + Only valid when protocol is TCP or UDP. + new_destination_port (int): + Destination port of a new connection. Only + valid when protocol is TCP or UDP. + subnet_uri (str): + Uri of proxy subnet. + network_uri (str): + URI of the network where connection is + proxied. + """ + + protocol: str = proto.Field( + proto.STRING, + number=1, + ) + old_source_ip: str = proto.Field( + proto.STRING, + number=2, + ) + new_source_ip: str = proto.Field( + proto.STRING, + number=3, + ) + old_destination_ip: str = proto.Field( + proto.STRING, + number=4, + ) + new_destination_ip: str = proto.Field( + proto.STRING, + number=5, + ) + old_source_port: int = proto.Field( + proto.INT32, + number=6, + ) + new_source_port: int = proto.Field( + proto.INT32, + number=7, + ) + old_destination_port: int = proto.Field( + proto.INT32, + number=8, + ) + new_destination_port: int = proto.Field( + proto.INT32, + number=9, + ) + subnet_uri: str = proto.Field( + proto.STRING, + number=10, + ) + network_uri: str = proto.Field( + proto.STRING, + number=11, + ) + + +class LoadBalancerBackendInfo(proto.Message): + r"""For display only. Metadata associated with the load balancer + backend. + + Attributes: + name (str): + Display name of the backend. For example, it + might be an instance name for the instance group + backends, or an IP address and port for zonal + network endpoint group backends. + instance_uri (str): + URI of the backend instance (if applicable). + Populated for instance group backends, and zonal + NEG backends. + backend_service_uri (str): + URI of the backend service this backend + belongs to (if applicable). + instance_group_uri (str): + URI of the instance group this backend + belongs to (if applicable). + network_endpoint_group_uri (str): + URI of the network endpoint group this + backend belongs to (if applicable). + backend_bucket_uri (str): + URI of the backend bucket this backend + targets (if applicable). + psc_service_attachment_uri (str): + URI of the PSC service attachment this PSC + NEG backend targets (if applicable). + psc_google_api_target (str): + PSC Google API target this PSC NEG backend + targets (if applicable). + health_check_uri (str): + URI of the health check attached to this + backend (if applicable). + health_check_firewalls_config_state (google.cloud.network_management_v1.types.LoadBalancerBackendInfo.HealthCheckFirewallsConfigState): + Output only. Health check firewalls + configuration state for the backend. This is a + result of the static firewall analysis + (verifying that health check traffic from + required IP ranges to the backend is allowed or + not). The backend might still be unhealthy even + if these firewalls are configured. Please refer + to the documentation for more information: + + https://cloud.google.com/load-balancing/docs/firewall-rules + """ + class HealthCheckFirewallsConfigState(proto.Enum): + r"""Health check firewalls configuration state enum. + + Values: + HEALTH_CHECK_FIREWALLS_CONFIG_STATE_UNSPECIFIED (0): + Configuration state unspecified. It usually + means that the backend has no health check + attached, or there was an unexpected + configuration error preventing Connectivity + tests from verifying health check configuration. + FIREWALLS_CONFIGURED (1): + Firewall rules (policies) allowing health + check traffic from all required IP ranges to the + backend are configured. + FIREWALLS_PARTIALLY_CONFIGURED (2): + Firewall rules (policies) allow health check + traffic only from a part of required IP ranges. + FIREWALLS_NOT_CONFIGURED (3): + Firewall rules (policies) deny health check + traffic from all required IP ranges to the + backend. + FIREWALLS_UNSUPPORTED (4): + The network contains firewall rules of + unsupported types, so Connectivity tests were + not able to verify health check configuration + status. Please refer to the documentation for + the list of unsupported configurations: + + https://cloud.google.com/network-intelligence-center/docs/connectivity-tests/concepts/overview#unsupported-configs + """ + HEALTH_CHECK_FIREWALLS_CONFIG_STATE_UNSPECIFIED = 0 + FIREWALLS_CONFIGURED = 1 + FIREWALLS_PARTIALLY_CONFIGURED = 2 + FIREWALLS_NOT_CONFIGURED = 3 + FIREWALLS_UNSUPPORTED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + instance_uri: str = proto.Field( + proto.STRING, + number=2, + ) + backend_service_uri: str = proto.Field( + proto.STRING, + number=3, + ) + instance_group_uri: str = proto.Field( + proto.STRING, + number=4, + ) + network_endpoint_group_uri: str = proto.Field( + proto.STRING, + number=5, + ) + backend_bucket_uri: str = proto.Field( + proto.STRING, + number=8, + ) + psc_service_attachment_uri: str = proto.Field( + proto.STRING, + number=9, + ) + psc_google_api_target: str = proto.Field( + proto.STRING, + number=10, + ) + health_check_uri: str = proto.Field( + proto.STRING, + number=6, + ) + health_check_firewalls_config_state: HealthCheckFirewallsConfigState = proto.Field( + proto.ENUM, + number=7, + enum=HealthCheckFirewallsConfigState, + ) + + +class StorageBucketInfo(proto.Message): + r"""For display only. Metadata associated with Storage Bucket. + + Attributes: + bucket (str): + Cloud Storage Bucket name. + """ + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ServerlessNegInfo(proto.Message): + r"""For display only. Metadata associated with the serverless + network endpoint group backend. + + Attributes: + neg_uri (str): + URI of the serverless network endpoint group. + """ + + neg_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/mypy.ini b/owl-bot-staging/google-cloud-network-management/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-management/v1/noxfile.py b/owl-bot-staging/google-cloud-network-management/v1/noxfile.py new file mode 100644 index 000000000000..e09f07364b34 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/noxfile.py @@ -0,0 +1,280 @@ +# -*- 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-network-management' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/network_management_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/network_management_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-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py new file mode 100644 index 000000000000..c74b86142f00 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py @@ -0,0 +1,57 @@ +# -*- 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 CreateConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_create_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.CreateConnectivityTestRequest( + parent="parent_value", + test_id="test_id_value", + ) + + # Make the request + operation = client.create_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py new file mode 100644 index 000000000000..c27c11cc246a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py @@ -0,0 +1,57 @@ +# -*- 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 CreateConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_create_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.CreateConnectivityTestRequest( + parent="parent_value", + test_id="test_id_value", + ) + + # Make the request + operation = client.create_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py new file mode 100644 index 000000000000..cc7d4daf1552 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_delete_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.DeleteConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py new file mode 100644 index 000000000000..00d6602a4aef --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_delete_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.DeleteConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py new file mode 100644 index 000000000000..85b70752cf16 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py @@ -0,0 +1,52 @@ +# -*- 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 GetConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_get_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.GetConnectivityTestRequest( + name="name_value", + ) + + # Make the request + response = await client.get_connectivity_test(request=request) + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py new file mode 100644 index 000000000000..40673d28a839 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py @@ -0,0 +1,52 @@ +# -*- 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 GetConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_get_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.GetConnectivityTestRequest( + name="name_value", + ) + + # Make the request + response = client.get_connectivity_test(request=request) + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py new file mode 100644 index 000000000000..15d2f1f0232f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py @@ -0,0 +1,53 @@ +# -*- 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 ListConnectivityTests +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_list_connectivity_tests(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.ListConnectivityTestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_connectivity_tests(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py new file mode 100644 index 000000000000..c595e917f169 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py @@ -0,0 +1,53 @@ +# -*- 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 ListConnectivityTests +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_list_connectivity_tests(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.ListConnectivityTestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_connectivity_tests(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py new file mode 100644 index 000000000000..9ba7e4c6759f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py @@ -0,0 +1,56 @@ +# -*- 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 RerunConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_rerun_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.RerunConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.rerun_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py new file mode 100644 index 000000000000..c726b18eda73 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py @@ -0,0 +1,56 @@ +# -*- 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 RerunConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_rerun_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.RerunConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.rerun_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py new file mode 100644 index 000000000000..a89f65bf0aa0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py @@ -0,0 +1,55 @@ +# -*- 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 UpdateConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_update_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.UpdateConnectivityTestRequest( + ) + + # Make the request + operation = client.update_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py new file mode 100644 index 000000000000..503f72cf246b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py @@ -0,0 +1,55 @@ +# -*- 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 UpdateConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_update_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.UpdateConnectivityTestRequest( + ) + + # Make the request + operation = client.update_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json new file mode 100644 index 000000000000..a6a39ec02f7f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json @@ -0,0 +1,997 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.networkmanagement.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-network-management", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.create_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.CreateConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "CreateConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.CreateConnectivityTestRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "test_id", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.network_management_v1.types.ConnectivityTest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for CreateConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.create_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.CreateConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "CreateConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.CreateConnectivityTestRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "test_id", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.network_management_v1.types.ConnectivityTest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for CreateConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.delete_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.DeleteConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "DeleteConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.DeleteConnectivityTestRequest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for DeleteConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.delete_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.DeleteConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "DeleteConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.DeleteConnectivityTestRequest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for DeleteConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.get_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.GetConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "GetConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.GetConnectivityTestRequest" + }, + { + "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.network_management_v1.types.ConnectivityTest", + "shortName": "get_connectivity_test" + }, + "description": "Sample for GetConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.get_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.GetConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "GetConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.GetConnectivityTestRequest" + }, + { + "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.network_management_v1.types.ConnectivityTest", + "shortName": "get_connectivity_test" + }, + "description": "Sample for GetConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.list_connectivity_tests", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.ListConnectivityTests", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "ListConnectivityTests" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.ListConnectivityTestsRequest" + }, + { + "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.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsAsyncPager", + "shortName": "list_connectivity_tests" + }, + "description": "Sample for ListConnectivityTests", + "file": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_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": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.list_connectivity_tests", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.ListConnectivityTests", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "ListConnectivityTests" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.ListConnectivityTestsRequest" + }, + { + "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.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsPager", + "shortName": "list_connectivity_tests" + }, + "description": "Sample for ListConnectivityTests", + "file": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_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": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.rerun_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.RerunConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "RerunConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.RerunConnectivityTestRequest" + }, + { + "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": "rerun_connectivity_test" + }, + "description": "Sample for RerunConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.rerun_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.RerunConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "RerunConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.RerunConnectivityTestRequest" + }, + { + "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": "rerun_connectivity_test" + }, + "description": "Sample for RerunConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.update_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.UpdateConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "UpdateConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.UpdateConnectivityTestRequest" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "resource", + "type": "google.cloud.network_management_v1.types.ConnectivityTest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for UpdateConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.update_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.UpdateConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "UpdateConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.UpdateConnectivityTestRequest" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "resource", + "type": "google.cloud.network_management_v1.types.ConnectivityTest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for UpdateConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py b/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py new file mode 100644 index 000000000000..33791cd81e72 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py @@ -0,0 +1,181 @@ +#! /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 network_managementCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_connectivity_test': ('parent', 'test_id', 'resource', ), + 'delete_connectivity_test': ('name', ), + 'get_connectivity_test': ('name', ), + 'list_connectivity_tests': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'rerun_connectivity_test': ('name', ), + 'update_connectivity_test': ('update_mask', 'resource', ), + } + + 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=network_managementCallTransformer(), +): + """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 network_management 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-network-management/v1/setup.py b/owl-bot-staging/google-cloud-network-management/v1/setup.py new file mode 100644 index 000000000000..110a46599b9a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/setup.py @@ -0,0 +1,99 @@ +# -*- 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-network-management' + + +description = "Google Cloud Network Management API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/network_management/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-management" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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-network-management/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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-network-management/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py new file mode 100644 index 000000000000..00328a587e68 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py @@ -0,0 +1,7462 @@ +# -*- 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.location import locations_pb2 +from google.cloud.network_management_v1.services.reachability_service import ReachabilityServiceAsyncClient +from google.cloud.network_management_v1.services.reachability_service import ReachabilityServiceClient +from google.cloud.network_management_v1.services.reachability_service import pagers +from google.cloud.network_management_v1.services.reachability_service import transports +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.cloud.network_management_v1.types import trace +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import 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 ReachabilityServiceClient._get_default_mtls_endpoint(None) is None + assert ReachabilityServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ReachabilityServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ReachabilityServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ReachabilityServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ReachabilityServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ReachabilityServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ReachabilityServiceClient._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 ReachabilityServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ReachabilityServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ReachabilityServiceClient._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 ReachabilityServiceClient._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 ReachabilityServiceClient._get_client_cert_source(None, False) is None + assert ReachabilityServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ReachabilityServiceClient._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 ReachabilityServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ReachabilityServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) +@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ReachabilityServiceClient._DEFAULT_UNIVERSE + default_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ReachabilityServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ReachabilityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT + assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "always") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT + assert ReachabilityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT + assert ReachabilityServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ReachabilityServiceClient._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 ReachabilityServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ReachabilityServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ReachabilityServiceClient._get_universe_domain(None, None) == ReachabilityServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ReachabilityServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ReachabilityServiceClient, "grpc"), + (ReachabilityServiceAsyncClient, "grpc_asyncio"), + (ReachabilityServiceClient, "rest"), +]) +def test_reachability_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networkmanagement.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networkmanagement.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ReachabilityServiceGrpcTransport, "grpc"), + (transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ReachabilityServiceRestTransport, "rest"), +]) +def test_reachability_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ReachabilityServiceClient, "grpc"), + (ReachabilityServiceAsyncClient, "grpc_asyncio"), + (ReachabilityServiceClient, "rest"), +]) +def test_reachability_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networkmanagement.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networkmanagement.googleapis.com' + ) + + +def test_reachability_service_client_get_transport_class(): + transport = ReachabilityServiceClient.get_transport_class() + available_transports = [ + transports.ReachabilityServiceGrpcTransport, + transports.ReachabilityServiceRestTransport, + ] + assert transport in available_transports + + transport = ReachabilityServiceClient.get_transport_class("grpc") + assert transport == transports.ReachabilityServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc"), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest"), +]) +@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) +@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) +def test_reachability_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ReachabilityServiceClient, '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(ReachabilityServiceClient, '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", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", "true"), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", "false"), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", "true"), + (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) +@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_reachability_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ReachabilityServiceClient, ReachabilityServiceAsyncClient +]) +@mock.patch.object(ReachabilityServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReachabilityServiceClient)) +@mock.patch.object(ReachabilityServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReachabilityServiceAsyncClient)) +def test_reachability_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_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", [ + ReachabilityServiceClient, ReachabilityServiceAsyncClient +]) +@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) +@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) +def test_reachability_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ReachabilityServiceClient._DEFAULT_UNIVERSE + default_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ReachabilityServiceClient._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", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc"), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest"), +]) +def test_reachability_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", grpc_helpers), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", None), +]) +def test_reachability_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_reachability_service_client_client_options_from_dict(): + with mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ReachabilityServiceClient( + 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", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", grpc_helpers), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_reachability_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networkmanagement.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="networkmanagement.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + reachability.ListConnectivityTestsRequest, + dict, +]) +def test_list_connectivity_tests(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connectivity_tests), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reachability.ListConnectivityTestsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.ListConnectivityTestsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConnectivityTestsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_connectivity_tests_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 = ReachabilityServiceClient( + 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 = reachability.ListConnectivityTestsRequest( + 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_connectivity_tests), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_connectivity_tests(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.ListConnectivityTestsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_connectivity_tests_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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_connectivity_tests in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_tests] = mock_rpc + request = {} + client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_connectivity_tests(request) + + # Establish that a new wrapper 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_connectivity_tests_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 = ReachabilityServiceAsyncClient( + 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_connectivity_tests 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_connectivity_tests] = mock_rpc + + request = {} + await client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_connectivity_tests(request) + + # Establish that a new wrapper 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_connectivity_tests_async(transport: str = 'grpc_asyncio', request_type=reachability.ListConnectivityTestsRequest): + client = ReachabilityServiceAsyncClient( + 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_connectivity_tests), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.ListConnectivityTestsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConnectivityTestsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_connectivity_tests_async_from_dict(): + await test_list_connectivity_tests_async(request_type=dict) + +def test_list_connectivity_tests_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.ListConnectivityTestsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + call.return_value = reachability.ListConnectivityTestsResponse() + client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_connectivity_tests_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.ListConnectivityTestsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse()) + await client.list_connectivity_tests(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_connectivity_tests_flattened(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reachability.ListConnectivityTestsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_connectivity_tests( + 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_connectivity_tests_flattened_error(): + client = ReachabilityServiceClient( + 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_connectivity_tests( + reachability.ListConnectivityTestsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_connectivity_tests_flattened_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reachability.ListConnectivityTestsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_connectivity_tests( + 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_connectivity_tests_flattened_error_async(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_tests( + reachability.ListConnectivityTestsRequest(), + parent='parent_value', + ) + + +def test_list_connectivity_tests_pager(transport_name: str = "grpc"): + client = ReachabilityServiceClient( + 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_connectivity_tests), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token='abc', + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token='def', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token='ghi', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_connectivity_tests(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, connectivity_test.ConnectivityTest) + for i in results) +def test_list_connectivity_tests_pages(transport_name: str = "grpc"): + client = ReachabilityServiceClient( + 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_connectivity_tests), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token='abc', + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token='def', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token='ghi', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), + RuntimeError, + ) + pages = list(client.list_connectivity_tests(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_connectivity_tests_async_pager(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token='abc', + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token='def', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token='ghi', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_connectivity_tests(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, connectivity_test.ConnectivityTest) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_connectivity_tests_async_pages(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token='abc', + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token='def', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token='ghi', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), + 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_connectivity_tests(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", [ + reachability.GetConnectivityTestRequest, + dict, +]) +def test_get_connectivity_test(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = connectivity_test.ConnectivityTest( + name='name_value', + description='description_value', + protocol='protocol_value', + related_projects=['related_projects_value'], + display_name='display_name_value', + bypass_firewall_checks=True, + ) + response = client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.GetConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, connectivity_test.ConnectivityTest) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.protocol == 'protocol_value' + assert response.related_projects == ['related_projects_value'] + assert response.display_name == 'display_name_value' + assert response.bypass_firewall_checks is True + + +def test_get_connectivity_test_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 = ReachabilityServiceClient( + 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 = reachability.GetConnectivityTestRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_connectivity_test(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.GetConnectivityTestRequest( + name='name_value', + ) + +def test_get_connectivity_test_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + request = {} + client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( + 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_connectivity_test 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_connectivity_test] = mock_rpc + + request = {} + await client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.GetConnectivityTestRequest): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest( + name='name_value', + description='description_value', + protocol='protocol_value', + related_projects=['related_projects_value'], + display_name='display_name_value', + bypass_firewall_checks=True, + )) + response = await client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.GetConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, connectivity_test.ConnectivityTest) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.protocol == 'protocol_value' + assert response.related_projects == ['related_projects_value'] + assert response.display_name == 'display_name_value' + assert response.bypass_firewall_checks is True + + +@pytest.mark.asyncio +async def test_get_connectivity_test_async_from_dict(): + await test_get_connectivity_test_async(request_type=dict) + +def test_get_connectivity_test_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.GetConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + call.return_value = connectivity_test.ConnectivityTest() + client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_connectivity_test_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.GetConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest()) + await client.get_connectivity_test(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_connectivity_test_flattened(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = connectivity_test.ConnectivityTest() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_connectivity_test( + 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_connectivity_test_flattened_error(): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.GetConnectivityTestRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_connectivity_test_flattened_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = connectivity_test.ConnectivityTest() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_connectivity_test( + 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_connectivity_test_flattened_error_async(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test( + reachability.GetConnectivityTestRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + reachability.CreateConnectivityTestRequest, + dict, +]) +def test_create_connectivity_test(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.CreateConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_connectivity_test_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 = ReachabilityServiceClient( + 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 = reachability.CreateConnectivityTestRequest( + parent='parent_value', + test_id='test_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_connectivity_test(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.CreateConnectivityTestRequest( + parent='parent_value', + test_id='test_id_value', + ) + +def test_create_connectivity_test_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + request = {} + client.create_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( + 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_connectivity_test 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_connectivity_test] = mock_rpc + + request = {} + await client.create_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.CreateConnectivityTestRequest): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test), + '__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_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.CreateConnectivityTestRequest() + 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_connectivity_test_async_from_dict(): + await test_create_connectivity_test_async(request_type=dict) + +def test_create_connectivity_test_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.CreateConnectivityTestRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_connectivity_test_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.CreateConnectivityTestRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_connectivity_test(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_connectivity_test_flattened(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__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_connectivity_test( + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].test_id + mock_val = 'test_id_value' + assert arg == mock_val + arg = args[0].resource + mock_val = connectivity_test.ConnectivityTest(name='name_value') + assert arg == mock_val + + +def test_create_connectivity_test_flattened_error(): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.CreateConnectivityTestRequest(), + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_connectivity_test_flattened_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__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_connectivity_test( + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].test_id + mock_val = 'test_id_value' + assert arg == mock_val + arg = args[0].resource + mock_val = connectivity_test.ConnectivityTest(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_connectivity_test_flattened_error_async(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test( + reachability.CreateConnectivityTestRequest(), + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + reachability.UpdateConnectivityTestRequest, + dict, +]) +def test_update_connectivity_test(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.UpdateConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_connectivity_test_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 = ReachabilityServiceClient( + 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 = reachability.UpdateConnectivityTestRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_connectivity_test(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.UpdateConnectivityTestRequest( + ) + +def test_update_connectivity_test_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + request = {} + client.update_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( + 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_connectivity_test 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_connectivity_test] = mock_rpc + + request = {} + await client.update_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.UpdateConnectivityTestRequest): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test), + '__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_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.UpdateConnectivityTestRequest() + 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_connectivity_test_async_from_dict(): + await test_update_connectivity_test_async(request_type=dict) + +def test_update_connectivity_test_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.UpdateConnectivityTestRequest() + + request.resource.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_connectivity_test_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.UpdateConnectivityTestRequest() + + request.resource.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource.name=name_value', + ) in kw['metadata'] + + +def test_update_connectivity_test_flattened(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__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_connectivity_test( + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(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].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + arg = args[0].resource + mock_val = connectivity_test.ConnectivityTest(name='name_value') + assert arg == mock_val + + +def test_update_connectivity_test_flattened_error(): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.UpdateConnectivityTestRequest(), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_connectivity_test_flattened_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__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_connectivity_test( + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(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].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + arg = args[0].resource + mock_val = connectivity_test.ConnectivityTest(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_connectivity_test_flattened_error_async(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test( + reachability.UpdateConnectivityTestRequest(), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + reachability.RerunConnectivityTestRequest, + dict, +]) +def test_rerun_connectivity_test(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rerun_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.RerunConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rerun_connectivity_test_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 = ReachabilityServiceClient( + 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 = reachability.RerunConnectivityTestRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.rerun_connectivity_test(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.RerunConnectivityTestRequest( + name='name_value', + ) + +def test_rerun_connectivity_test_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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.rerun_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.rerun_connectivity_test] = mock_rpc + request = {} + client.rerun_connectivity_test(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.rerun_connectivity_test(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_rerun_connectivity_test_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 = ReachabilityServiceAsyncClient( + 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.rerun_connectivity_test 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.rerun_connectivity_test] = mock_rpc + + request = {} + await client.rerun_connectivity_test(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.rerun_connectivity_test(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_rerun_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.RerunConnectivityTestRequest): + client = ReachabilityServiceAsyncClient( + 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.rerun_connectivity_test), + '__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.rerun_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.RerunConnectivityTestRequest() + 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_rerun_connectivity_test_async_from_dict(): + await test_rerun_connectivity_test_async(request_type=dict) + +def test_rerun_connectivity_test_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.RerunConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rerun_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_rerun_connectivity_test_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.RerunConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rerun_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + reachability.DeleteConnectivityTestRequest, + dict, +]) +def test_delete_connectivity_test(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.DeleteConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_connectivity_test_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 = ReachabilityServiceClient( + 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 = reachability.DeleteConnectivityTestRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_connectivity_test(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.DeleteConnectivityTestRequest( + name='name_value', + ) + +def test_delete_connectivity_test_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + request = {} + client.delete_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( + 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_connectivity_test 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_connectivity_test] = mock_rpc + + request = {} + await client.delete_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.DeleteConnectivityTestRequest): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test), + '__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_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.DeleteConnectivityTestRequest() + 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_connectivity_test_async_from_dict(): + await test_delete_connectivity_test_async(request_type=dict) + +def test_delete_connectivity_test_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.DeleteConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_connectivity_test_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.DeleteConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_connectivity_test(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_connectivity_test_flattened(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__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_connectivity_test( + 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_connectivity_test_flattened_error(): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.DeleteConnectivityTestRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_connectivity_test_flattened_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__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_connectivity_test( + 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_connectivity_test_flattened_error_async(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test( + reachability.DeleteConnectivityTestRequest(), + name='name_value', + ) + + +def test_list_connectivity_tests_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 = ReachabilityServiceClient( + 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_connectivity_tests in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_tests] = mock_rpc + + request = {} + client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_connectivity_tests(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_connectivity_tests_rest_required_fields(request_type=reachability.ListConnectivityTestsRequest): + transport_class = transports.ReachabilityServiceRestTransport + + 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_connectivity_tests._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_connectivity_tests._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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reachability.ListConnectivityTestsResponse() + # Mock the http request call 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_connectivity_tests_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_connectivity_tests._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_connectivity_tests_rest_flattened(): + client = ReachabilityServiceClient( + 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 = reachability.ListConnectivityTestsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/global'} + + # 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(**mock_args) + + # Establish that the underlying call 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/global}/connectivityTests" % client.transport._host, args[1]) + + +def test_list_connectivity_tests_rest_flattened_error(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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_connectivity_tests( + reachability.ListConnectivityTestsRequest(), + parent='parent_value', + ) + + +def test_list_connectivity_tests_rest_pager(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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 = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token='abc', + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token='def', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token='ghi', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(reachability.ListConnectivityTestsResponse.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/global'} + + pager = client.list_connectivity_tests(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, connectivity_test.ConnectivityTest) + for i in results) + + pages = list(client.list_connectivity_tests(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_connectivity_test_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 = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + + request = {} + client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.GetConnectivityTestRequest): + transport_class = transports.ReachabilityServiceRestTransport + + 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = connectivity_test.ConnectivityTest() + # Mock the http request call 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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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 = connectivity_test.ConnectivityTest() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/global/connectivityTests/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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(**mock_args) + + # Establish that the underlying call 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/global/connectivityTests/*}" % client.transport._host, args[1]) + + +def test_get_connectivity_test_rest_flattened_error(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.GetConnectivityTestRequest(), + name='name_value', + ) + + +def test_create_connectivity_test_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 = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + + request = {} + client.create_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.CreateConnectivityTestRequest): + transport_class = transports.ReachabilityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["test_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 "testId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_connectivity_test._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "testId" in jsonified_request + assert jsonified_request["testId"] == request_init["test_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["testId"] = 'test_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_connectivity_test._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("test_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 "testId" in jsonified_request + assert jsonified_request["testId"] == 'test_id_value' + + client = ReachabilityServiceClient( + 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_connectivity_test(request) + + expected_params = [ + ( + "testId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(("testId", )) & set(("parent", "testId", "resource", ))) + + +def test_create_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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/global'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(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.create_connectivity_test(**mock_args) + + # Establish that the underlying call 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/global}/connectivityTests" % client.transport._host, args[1]) + + +def test_create_connectivity_test_rest_flattened_error(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.CreateConnectivityTestRequest(), + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + +def test_update_connectivity_test_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 = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + + request = {} + client.update_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.UpdateConnectivityTestRequest): + transport_class = transports.ReachabilityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_connectivity_test._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_connectivity_test._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_connectivity_test(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", "resource", ))) + + +def test_update_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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 = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(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.update_connectivity_test(**mock_args) + + # Establish that the underlying call 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/{resource.name=projects/*/locations/global/connectivityTests/*}" % client.transport._host, args[1]) + + +def test_update_connectivity_test_rest_flattened_error(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.UpdateConnectivityTestRequest(), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + +def test_rerun_connectivity_test_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 = ReachabilityServiceClient( + 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.rerun_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.rerun_connectivity_test] = mock_rpc + + request = {} + client.rerun_connectivity_test(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.rerun_connectivity_test(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_rerun_connectivity_test_rest_required_fields(request_type=reachability.RerunConnectivityTestRequest): + transport_class = transports.ReachabilityServiceRestTransport + + 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()).rerun_connectivity_test._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()).rerun_connectivity_test._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 = ReachabilityServiceClient( + 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.rerun_connectivity_test(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_rerun_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.rerun_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_connectivity_test_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 = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + + request = {} + client.delete_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.DeleteConnectivityTestRequest): + transport_class = transports.ReachabilityServiceRestTransport + + 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( + 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_connectivity_test(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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/global/connectivityTests/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_connectivity_test(**mock_args) + + # Establish that the underlying call 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/global/connectivityTests/*}" % client.transport._host, args[1]) + + +def test_delete_connectivity_test_rest_flattened_error(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.DeleteConnectivityTestRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ReachabilityServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ReachabilityServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ReachabilityServiceGrpcTransport, + transports.ReachabilityServiceGrpcAsyncIOTransport, + transports.ReachabilityServiceRestTransport, +]) +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 = ReachabilityServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ReachabilityServiceClient( + 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_connectivity_tests_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + call.return_value = reachability.ListConnectivityTestsResponse() + client.list_connectivity_tests(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.ListConnectivityTestsRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + call.return_value = connectivity_test.ConnectivityTest() + client.get_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.GetConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.CreateConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.UpdateConnectivityTestRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rerun_connectivity_test_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rerun_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.RerunConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.DeleteConnectivityTestRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ReachabilityServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_tests_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_connectivity_tests(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.ListConnectivityTestsRequest() + + assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest( + name='name_value', + description='description_value', + protocol='protocol_value', + related_projects=['related_projects_value'], + display_name='display_name_value', + bypass_firewall_checks=True, + )) + await client.get_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.GetConnectivityTestRequest() + + assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__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_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.CreateConnectivityTestRequest() + + assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__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_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.UpdateConnectivityTestRequest() + + assert args[0] == request_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_rerun_connectivity_test_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__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.rerun_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.RerunConnectivityTestRequest() + + assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__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_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.DeleteConnectivityTestRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ReachabilityServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_connectivity_tests_rest_bad_request(request_type=reachability.ListConnectivityTestsRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/global'} + 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_connectivity_tests(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.ListConnectivityTestsRequest, + dict, +]) +def test_list_connectivity_tests_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/global'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = reachability.ListConnectivityTestsResponse( + 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConnectivityTestsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_connectivity_tests_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_list_connectivity_tests") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_list_connectivity_tests") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.ListConnectivityTestsRequest.pb(reachability.ListConnectivityTestsRequest()) + 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 = reachability.ListConnectivityTestsResponse.to_json(reachability.ListConnectivityTestsResponse()) + req.return_value.content = return_value + + request = reachability.ListConnectivityTestsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reachability.ListConnectivityTestsResponse() + + client.list_connectivity_tests(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_connectivity_test_rest_bad_request(request_type=reachability.GetConnectivityTestRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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_connectivity_test(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.GetConnectivityTestRequest, + dict, +]) +def test_get_connectivity_test_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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 = connectivity_test.ConnectivityTest( + name='name_value', + description='description_value', + protocol='protocol_value', + related_projects=['related_projects_value'], + display_name='display_name_value', + bypass_firewall_checks=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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, connectivity_test.ConnectivityTest) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.protocol == 'protocol_value' + assert response.related_projects == ['related_projects_value'] + assert response.display_name == 'display_name_value' + assert response.bypass_firewall_checks is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_get_connectivity_test") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_get_connectivity_test") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.GetConnectivityTestRequest.pb(reachability.GetConnectivityTestRequest()) + 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 = connectivity_test.ConnectivityTest.to_json(connectivity_test.ConnectivityTest()) + req.return_value.content = return_value + + request = reachability.GetConnectivityTestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = connectivity_test.ConnectivityTest() + + client.get_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_connectivity_test_rest_bad_request(request_type=reachability.CreateConnectivityTestRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/global'} + 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_connectivity_test(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.CreateConnectivityTestRequest, + dict, +]) +def test_create_connectivity_test_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/global'} + request_init["resource"] = {'name': 'name_value', 'description': 'description_value', 'source': {'ip_address': 'ip_address_value', 'port': 453, 'instance': 'instance_value', 'forwarding_rule': 'forwarding_rule_value', 'forwarding_rule_target': 1, 'load_balancer_id': 'load_balancer_id_value', 'load_balancer_type': 1, 'gke_master_cluster': 'gke_master_cluster_value', 'fqdn': 'fqdn_value', 'cloud_sql_instance': 'cloud_sql_instance_value', 'redis_instance': 'redis_instance_value', 'redis_cluster': 'redis_cluster_value', 'cloud_function': {'uri': 'uri_value'}, 'app_engine_version': {'uri': 'uri_value'}, 'cloud_run_revision': {'uri': 'uri_value'}, 'network': 'network_value', 'network_type': 1, 'project_id': 'project_id_value'}, 'destination': {}, 'protocol': 'protocol_value', 'related_projects': ['related_projects_value1', 'related_projects_value2'], 'display_name': 'display_name_value', 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'reachability_details': {'result': 1, 'verify_time': {}, 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'traces': [{'endpoint_info': {'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'protocol': 'protocol_value', 'source_port': 1205, 'destination_port': 1734, 'source_network_uri': 'source_network_uri_value', 'destination_network_uri': 'destination_network_uri_value', 'source_agent_uri': 'source_agent_uri_value'}, 'steps': [{'description': 'description_value', 'state': 1, 'causes_drop': True, 'project_id': 'project_id_value', 'instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'interface': 'interface_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'network_tags': ['network_tags_value1', 'network_tags_value2'], 'service_account': 'service_account_value', 'psc_network_attachment_uri': 'psc_network_attachment_uri_value'}, 'firewall': {'display_name': 'display_name_value', 'uri': 'uri_value', 'direction': 'direction_value', 'action': 'action_value', 'priority': 898, 'network_uri': 'network_uri_value', 'target_tags': ['target_tags_value1', 'target_tags_value2'], 'target_service_accounts': ['target_service_accounts_value1', 'target_service_accounts_value2'], 'policy': 'policy_value', 'policy_uri': 'policy_uri_value', 'firewall_rule_type': 1}, 'route': {'route_type': 1, 'next_hop_type': 1, 'route_scope': 1, 'display_name': 'display_name_value', 'uri': 'uri_value', 'region': 'region_value', 'dest_ip_range': 'dest_ip_range_value', 'next_hop': 'next_hop_value', 'network_uri': 'network_uri_value', 'priority': 898, 'instance_tags': ['instance_tags_value1', 'instance_tags_value2'], 'src_ip_range': 'src_ip_range_value', 'dest_port_ranges': ['dest_port_ranges_value1', 'dest_port_ranges_value2'], 'src_port_ranges': ['src_port_ranges_value1', 'src_port_ranges_value2'], 'protocols': ['protocols_value1', 'protocols_value2'], 'ncc_hub_uri': 'ncc_hub_uri_value', 'ncc_spoke_uri': 'ncc_spoke_uri_value', 'advertised_route_source_router_uri': 'advertised_route_source_router_uri_value', 'advertised_route_next_hop_uri': 'advertised_route_next_hop_uri_value'}, 'endpoint': {}, 'google_service': {'source_ip': 'source_ip_value', 'google_service_type': 1}, 'forwarding_rule': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_protocol': 'matched_protocol_value', 'matched_port_range': 'matched_port_range_value', 'vip': 'vip_value', 'target': 'target_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'load_balancer_name': 'load_balancer_name_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'vpn_gateway': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'ip_address': 'ip_address_value', 'vpn_tunnel_uri': 'vpn_tunnel_uri_value', 'region': 'region_value'}, 'vpn_tunnel': {'display_name': 'display_name_value', 'uri': 'uri_value', 'source_gateway': 'source_gateway_value', 'remote_gateway': 'remote_gateway_value', 'remote_gateway_ip': 'remote_gateway_ip_value', 'source_gateway_ip': 'source_gateway_ip_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'routing_type': 1}, 'vpc_connector': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value'}, 'deliver': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'storage_bucket': 'storage_bucket_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'forward': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value'}, 'abort': {'cause': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'projects_missing_permission': ['projects_missing_permission_value1', 'projects_missing_permission_value2']}, 'drop': {'cause': 1, 'resource_uri': 'resource_uri_value', 'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'region': 'region_value'}, 'load_balancer': {'load_balancer_type': 1, 'health_check_uri': 'health_check_uri_value', 'backends': [{'display_name': 'display_name_value', 'uri': 'uri_value', 'health_check_firewall_state': 1, 'health_check_allowing_firewall_rules': ['health_check_allowing_firewall_rules_value1', 'health_check_allowing_firewall_rules_value2'], 'health_check_blocking_firewall_rules': ['health_check_blocking_firewall_rules_value1', 'health_check_blocking_firewall_rules_value2']}], 'backend_type': 1, 'backend_uri': 'backend_uri_value'}, 'network': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_subnet_uri': 'matched_subnet_uri_value', 'matched_ip_range': 'matched_ip_range_value', 'region': 'region_value'}, 'gke_master': {'cluster_uri': 'cluster_uri_value', 'cluster_network_uri': 'cluster_network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'dns_endpoint': 'dns_endpoint_value'}, 'cloud_sql_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'region': 'region_value'}, 'redis_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'primary_endpoint_ip': 'primary_endpoint_ip_value', 'read_endpoint_ip': 'read_endpoint_ip_value', 'region': 'region_value'}, 'redis_cluster': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'discovery_endpoint_ip_address': 'discovery_endpoint_ip_address_value', 'secondary_endpoint_ip_address': 'secondary_endpoint_ip_address_value', 'location': 'location_value'}, 'cloud_function': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'version_id': 1074}, 'app_engine_version': {'display_name': 'display_name_value', 'uri': 'uri_value', 'runtime': 'runtime_value', 'environment': 'environment_value'}, 'cloud_run_revision': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'service_uri': 'service_uri_value'}, 'nat': {'type_': 1, 'protocol': 'protocol_value', 'network_uri': 'network_uri_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'router_uri': 'router_uri_value', 'nat_gateway_name': 'nat_gateway_name_value'}, 'proxy_connection': {'protocol': 'protocol_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'subnet_uri': 'subnet_uri_value', 'network_uri': 'network_uri_value'}, 'load_balancer_backend_info': {'name': 'name_value', 'instance_uri': 'instance_uri_value', 'backend_service_uri': 'backend_service_uri_value', 'instance_group_uri': 'instance_group_uri_value', 'network_endpoint_group_uri': 'network_endpoint_group_uri_value', 'backend_bucket_uri': 'backend_bucket_uri_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value', 'health_check_uri': 'health_check_uri_value', 'health_check_firewalls_config_state': 1}, 'storage_bucket': {'bucket': 'bucket_value'}, 'serverless_neg': {'neg_uri': 'neg_uri_value'}}], 'forward_trace_id': 1679}]}, 'probing_details': {'result': 1, 'verify_time': {}, 'error': {}, 'abort_cause': 1, 'sent_probe_count': 1721, 'successful_probe_count': 2367, 'endpoint_info': {}, 'probing_latency': {'latency_percentiles': [{'percent': 753, 'latency_micros': 1500}]}, 'destination_egress_location': {'metropolitan_area': 'metropolitan_area_value'}}, 'bypass_firewall_checks': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = reachability.CreateConnectivityTestRequest.meta.fields["resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_create_connectivity_test") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_create_connectivity_test") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.CreateConnectivityTestRequest.pb(reachability.CreateConnectivityTestRequest()) + 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 = reachability.CreateConnectivityTestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_connectivity_test_rest_bad_request(request_type=reachability.UpdateConnectivityTestRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/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.update_connectivity_test(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.UpdateConnectivityTestRequest, + dict, +]) +def test_update_connectivity_test_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/sample2'}} + request_init["resource"] = {'name': 'projects/sample1/locations/global/connectivityTests/sample2', 'description': 'description_value', 'source': {'ip_address': 'ip_address_value', 'port': 453, 'instance': 'instance_value', 'forwarding_rule': 'forwarding_rule_value', 'forwarding_rule_target': 1, 'load_balancer_id': 'load_balancer_id_value', 'load_balancer_type': 1, 'gke_master_cluster': 'gke_master_cluster_value', 'fqdn': 'fqdn_value', 'cloud_sql_instance': 'cloud_sql_instance_value', 'redis_instance': 'redis_instance_value', 'redis_cluster': 'redis_cluster_value', 'cloud_function': {'uri': 'uri_value'}, 'app_engine_version': {'uri': 'uri_value'}, 'cloud_run_revision': {'uri': 'uri_value'}, 'network': 'network_value', 'network_type': 1, 'project_id': 'project_id_value'}, 'destination': {}, 'protocol': 'protocol_value', 'related_projects': ['related_projects_value1', 'related_projects_value2'], 'display_name': 'display_name_value', 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'reachability_details': {'result': 1, 'verify_time': {}, 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'traces': [{'endpoint_info': {'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'protocol': 'protocol_value', 'source_port': 1205, 'destination_port': 1734, 'source_network_uri': 'source_network_uri_value', 'destination_network_uri': 'destination_network_uri_value', 'source_agent_uri': 'source_agent_uri_value'}, 'steps': [{'description': 'description_value', 'state': 1, 'causes_drop': True, 'project_id': 'project_id_value', 'instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'interface': 'interface_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'network_tags': ['network_tags_value1', 'network_tags_value2'], 'service_account': 'service_account_value', 'psc_network_attachment_uri': 'psc_network_attachment_uri_value'}, 'firewall': {'display_name': 'display_name_value', 'uri': 'uri_value', 'direction': 'direction_value', 'action': 'action_value', 'priority': 898, 'network_uri': 'network_uri_value', 'target_tags': ['target_tags_value1', 'target_tags_value2'], 'target_service_accounts': ['target_service_accounts_value1', 'target_service_accounts_value2'], 'policy': 'policy_value', 'policy_uri': 'policy_uri_value', 'firewall_rule_type': 1}, 'route': {'route_type': 1, 'next_hop_type': 1, 'route_scope': 1, 'display_name': 'display_name_value', 'uri': 'uri_value', 'region': 'region_value', 'dest_ip_range': 'dest_ip_range_value', 'next_hop': 'next_hop_value', 'network_uri': 'network_uri_value', 'priority': 898, 'instance_tags': ['instance_tags_value1', 'instance_tags_value2'], 'src_ip_range': 'src_ip_range_value', 'dest_port_ranges': ['dest_port_ranges_value1', 'dest_port_ranges_value2'], 'src_port_ranges': ['src_port_ranges_value1', 'src_port_ranges_value2'], 'protocols': ['protocols_value1', 'protocols_value2'], 'ncc_hub_uri': 'ncc_hub_uri_value', 'ncc_spoke_uri': 'ncc_spoke_uri_value', 'advertised_route_source_router_uri': 'advertised_route_source_router_uri_value', 'advertised_route_next_hop_uri': 'advertised_route_next_hop_uri_value'}, 'endpoint': {}, 'google_service': {'source_ip': 'source_ip_value', 'google_service_type': 1}, 'forwarding_rule': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_protocol': 'matched_protocol_value', 'matched_port_range': 'matched_port_range_value', 'vip': 'vip_value', 'target': 'target_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'load_balancer_name': 'load_balancer_name_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'vpn_gateway': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'ip_address': 'ip_address_value', 'vpn_tunnel_uri': 'vpn_tunnel_uri_value', 'region': 'region_value'}, 'vpn_tunnel': {'display_name': 'display_name_value', 'uri': 'uri_value', 'source_gateway': 'source_gateway_value', 'remote_gateway': 'remote_gateway_value', 'remote_gateway_ip': 'remote_gateway_ip_value', 'source_gateway_ip': 'source_gateway_ip_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'routing_type': 1}, 'vpc_connector': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value'}, 'deliver': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'storage_bucket': 'storage_bucket_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'forward': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value'}, 'abort': {'cause': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'projects_missing_permission': ['projects_missing_permission_value1', 'projects_missing_permission_value2']}, 'drop': {'cause': 1, 'resource_uri': 'resource_uri_value', 'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'region': 'region_value'}, 'load_balancer': {'load_balancer_type': 1, 'health_check_uri': 'health_check_uri_value', 'backends': [{'display_name': 'display_name_value', 'uri': 'uri_value', 'health_check_firewall_state': 1, 'health_check_allowing_firewall_rules': ['health_check_allowing_firewall_rules_value1', 'health_check_allowing_firewall_rules_value2'], 'health_check_blocking_firewall_rules': ['health_check_blocking_firewall_rules_value1', 'health_check_blocking_firewall_rules_value2']}], 'backend_type': 1, 'backend_uri': 'backend_uri_value'}, 'network': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_subnet_uri': 'matched_subnet_uri_value', 'matched_ip_range': 'matched_ip_range_value', 'region': 'region_value'}, 'gke_master': {'cluster_uri': 'cluster_uri_value', 'cluster_network_uri': 'cluster_network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'dns_endpoint': 'dns_endpoint_value'}, 'cloud_sql_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'region': 'region_value'}, 'redis_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'primary_endpoint_ip': 'primary_endpoint_ip_value', 'read_endpoint_ip': 'read_endpoint_ip_value', 'region': 'region_value'}, 'redis_cluster': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'discovery_endpoint_ip_address': 'discovery_endpoint_ip_address_value', 'secondary_endpoint_ip_address': 'secondary_endpoint_ip_address_value', 'location': 'location_value'}, 'cloud_function': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'version_id': 1074}, 'app_engine_version': {'display_name': 'display_name_value', 'uri': 'uri_value', 'runtime': 'runtime_value', 'environment': 'environment_value'}, 'cloud_run_revision': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'service_uri': 'service_uri_value'}, 'nat': {'type_': 1, 'protocol': 'protocol_value', 'network_uri': 'network_uri_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'router_uri': 'router_uri_value', 'nat_gateway_name': 'nat_gateway_name_value'}, 'proxy_connection': {'protocol': 'protocol_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'subnet_uri': 'subnet_uri_value', 'network_uri': 'network_uri_value'}, 'load_balancer_backend_info': {'name': 'name_value', 'instance_uri': 'instance_uri_value', 'backend_service_uri': 'backend_service_uri_value', 'instance_group_uri': 'instance_group_uri_value', 'network_endpoint_group_uri': 'network_endpoint_group_uri_value', 'backend_bucket_uri': 'backend_bucket_uri_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value', 'health_check_uri': 'health_check_uri_value', 'health_check_firewalls_config_state': 1}, 'storage_bucket': {'bucket': 'bucket_value'}, 'serverless_neg': {'neg_uri': 'neg_uri_value'}}], 'forward_trace_id': 1679}]}, 'probing_details': {'result': 1, 'verify_time': {}, 'error': {}, 'abort_cause': 1, 'sent_probe_count': 1721, 'successful_probe_count': 2367, 'endpoint_info': {}, 'probing_latency': {'latency_percentiles': [{'percent': 753, 'latency_micros': 1500}]}, 'destination_egress_location': {'metropolitan_area': 'metropolitan_area_value'}}, 'bypass_firewall_checks': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = reachability.UpdateConnectivityTestRequest.meta.fields["resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_update_connectivity_test") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_update_connectivity_test") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.UpdateConnectivityTestRequest.pb(reachability.UpdateConnectivityTestRequest()) + 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 = reachability.UpdateConnectivityTestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_rerun_connectivity_test_rest_bad_request(request_type=reachability.RerunConnectivityTestRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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.rerun_connectivity_test(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.RerunConnectivityTestRequest, + dict, +]) +def test_rerun_connectivity_test_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # 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.rerun_connectivity_test(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_rerun_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_rerun_connectivity_test") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_rerun_connectivity_test") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.RerunConnectivityTestRequest.pb(reachability.RerunConnectivityTestRequest()) + 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 = reachability.RerunConnectivityTestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.rerun_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_connectivity_test_rest_bad_request(request_type=reachability.DeleteConnectivityTestRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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.delete_connectivity_test(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.DeleteConnectivityTestRequest, + dict, +]) +def test_delete_connectivity_test_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_delete_connectivity_test") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_delete_connectivity_test") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.DeleteConnectivityTestRequest.pb(reachability.DeleteConnectivityTestRequest()) + 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 = reachability.DeleteConnectivityTestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_connectivity_test(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 = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + 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_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/global'}, 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/global'} + 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 = ReachabilityServiceClient( + 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_connectivity_tests_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + client.list_connectivity_tests(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.ListConnectivityTestsRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + client.get_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.GetConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__call__') as call: + client.create_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.CreateConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__call__') as call: + client.update_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.UpdateConnectivityTestRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rerun_connectivity_test_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + client.rerun_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.RerunConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__call__') as call: + client.delete_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.DeleteConnectivityTestRequest() + + assert args[0] == request_msg + + +def test_reachability_service_rest_lro_client(): + client = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ReachabilityServiceGrpcTransport, + ) + +def test_reachability_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ReachabilityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_reachability_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ReachabilityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_connectivity_tests', + 'get_connectivity_test', + 'create_connectivity_test', + 'update_connectivity_test', + 'rerun_connectivity_test', + 'delete_connectivity_test', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_reachability_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReachabilityServiceTransport( + 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_reachability_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReachabilityServiceTransport() + adc.assert_called_once() + + +def test_reachability_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ReachabilityServiceClient() + 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.ReachabilityServiceGrpcTransport, + transports.ReachabilityServiceGrpcAsyncIOTransport, + ], +) +def test_reachability_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ReachabilityServiceGrpcTransport, + transports.ReachabilityServiceGrpcAsyncIOTransport, + transports.ReachabilityServiceRestTransport, + ], +) +def test_reachability_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ReachabilityServiceGrpcTransport, grpc_helpers), + (transports.ReachabilityServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_reachability_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "networkmanagement.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="networkmanagement.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) +def test_reachability_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_reachability_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ReachabilityServiceRestTransport ( + 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_reachability_service_host_no_port(transport_name): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networkmanagement.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networkmanagement.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networkmanagement.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_reachability_service_host_with_port(transport_name): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networkmanagement.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networkmanagement.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networkmanagement.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_reachability_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ReachabilityServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ReachabilityServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_connectivity_tests._session + session2 = client2.transport.list_connectivity_tests._session + assert session1 != session2 + session1 = client1.transport.get_connectivity_test._session + session2 = client2.transport.get_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.create_connectivity_test._session + session2 = client2.transport.create_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.update_connectivity_test._session + session2 = client2.transport.update_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.rerun_connectivity_test._session + session2 = client2.transport.rerun_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.delete_connectivity_test._session + session2 = client2.transport.delete_connectivity_test._session + assert session1 != session2 +def test_reachability_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ReachabilityServiceGrpcTransport( + 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_reachability_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ReachabilityServiceGrpcAsyncIOTransport( + 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.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) +def test_reachability_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) +def test_reachability_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_reachability_service_grpc_lro_client(): + client = ReachabilityServiceClient( + 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_reachability_service_grpc_lro_async_client(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test_path(): + project = "squid" + test = "clam" + expected = "projects/{project}/locations/global/connectivityTests/{test}".format(project=project, test=test, ) + actual = ReachabilityServiceClient.connectivity_test_path(project, test) + assert expected == actual + + +def test_parse_connectivity_test_path(): + expected = { + "project": "whelk", + "test": "octopus", + } + path = ReachabilityServiceClient.connectivity_test_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.parse_connectivity_test_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ReachabilityServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ReachabilityServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ReachabilityServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ReachabilityServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ReachabilityServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ReachabilityServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ReachabilityServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ReachabilityServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ReachabilityServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ReachabilityServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.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.ReachabilityServiceTransport, '_prep_wrapped_messages') as prep: + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ReachabilityServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ReachabilityServiceClient.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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + 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", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From 66766836a1dfc973251b18b0769909beda478caf Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 14 Nov 2024 08:59:31 +0000 Subject: [PATCH 2/4] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../v1/.coveragerc | 13 - .../v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../reachability_service.rst | 10 - .../docs/network_management_v1/services_.rst | 6 - .../v1/docs/network_management_v1/types_.rst | 6 - .../cloud/network_management/__init__.py | 117 - .../cloud/network_management/gapic_version.py | 16 - .../google/cloud/network_management/py.typed | 2 - .../cloud/network_management_v1/__init__.py | 118 - .../network_management_v1/gapic_metadata.json | 118 - .../network_management_v1/gapic_version.py | 16 - .../cloud/network_management_v1/py.typed | 2 - .../services/__init__.py | 15 - .../services/reachability_service/__init__.py | 22 - .../reachability_service/async_client.py | 1597 ---- .../services/reachability_service/client.py | 1917 ----- .../services/reachability_service/pagers.py | 163 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../reachability_service/transports/base.py | 362 - .../reachability_service/transports/grpc.py | 660 -- .../transports/grpc_asyncio.py | 751 -- .../reachability_service/transports/rest.py | 1714 ---- .../transports/rest_base.py | 588 -- .../network_management_v1/types/__init__.py | 114 - .../types/connectivity_test.py | 735 -- .../types/reachability.py | 293 - .../network_management_v1/types/trace.py | 3164 ------- .../v1/mypy.ini | 3 - .../v1/noxfile.py | 280 - ..._service_create_connectivity_test_async.py | 57 - ...y_service_create_connectivity_test_sync.py | 57 - ..._service_delete_connectivity_test_async.py | 56 - ...y_service_delete_connectivity_test_sync.py | 56 - ...ity_service_get_connectivity_test_async.py | 52 - ...lity_service_get_connectivity_test_sync.py | 52 - ...y_service_list_connectivity_tests_async.py | 53 - ...ty_service_list_connectivity_tests_sync.py | 53 - ...y_service_rerun_connectivity_test_async.py | 56 - ...ty_service_rerun_connectivity_test_sync.py | 56 - ..._service_update_connectivity_test_async.py | 55 - ...y_service_update_connectivity_test_sync.py | 55 - ...ata_google.cloud.networkmanagement.v1.json | 997 --- .../fixup_network_management_v1_keywords.py | 181 - .../v1/setup.py | 99 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.13.txt | 7 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/network_management_v1/__init__.py | 16 - .../test_reachability_service.py | 7462 ----------------- .../cloud/network_management/gapic_version.py | 2 +- .../network_management_v1/gapic_version.py | 2 +- ...ata_google.cloud.networkmanagement.v1.json | 2 +- 65 files changed, 3 insertions(+), 22836 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/.coveragerc b/owl-bot-staging/google-cloud-network-management/v1/.coveragerc deleted file mode 100644 index 20f78aac3034..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/network_management/__init__.py - google/cloud/network_management/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-network-management/v1/.flake8 b/owl-bot-staging/google-cloud-network-management/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in b/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in deleted file mode 100644 index 240002b7c5c7..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/network_management *.py -recursive-include google/cloud/network_management_v1 *.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/README.rst b/owl-bot-staging/google-cloud-network-management/v1/README.rst deleted file mode 100644 index 264724cca11b..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Network Management 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 Network Management 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-network-management/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py b/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py deleted file mode 100644 index a303b54b23a8..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-network-management documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-network-management" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-network-management-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-network-management.tex", - u"google-cloud-network-management Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-network-management", - u"Google Cloud Network Management 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-network-management", - u"google-cloud-network-management Documentation", - author, - "google-cloud-network-management", - "GAPIC library for Google Cloud Network Management 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-network-management/v1/docs/index.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/index.rst deleted file mode 100644 index df608d7805a8..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - network_management_v1/services_ - network_management_v1/types_ diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst deleted file mode 100644 index 1d3502a632c9..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ReachabilityService -------------------------------------- - -.. automodule:: google.cloud.network_management_v1.services.reachability_service - :members: - :inherited-members: - -.. automodule:: google.cloud.network_management_v1.services.reachability_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst deleted file mode 100644 index e26ca50e5fc4..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Network Management v1 API -=================================================== -.. toctree:: - :maxdepth: 2 - - reachability_service diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst deleted file mode 100644 index 11bcca7b4b58..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Network Management v1 API -================================================ - -.. automodule:: google.cloud.network_management_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py deleted file mode 100644 index 23a237dd11fa..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py +++ /dev/null @@ -1,117 +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.network_management import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.network_management_v1.services.reachability_service.client import ReachabilityServiceClient -from google.cloud.network_management_v1.services.reachability_service.async_client import ReachabilityServiceAsyncClient - -from google.cloud.network_management_v1.types.connectivity_test import ConnectivityTest -from google.cloud.network_management_v1.types.connectivity_test import Endpoint -from google.cloud.network_management_v1.types.connectivity_test import LatencyDistribution -from google.cloud.network_management_v1.types.connectivity_test import LatencyPercentile -from google.cloud.network_management_v1.types.connectivity_test import ProbingDetails -from google.cloud.network_management_v1.types.connectivity_test import ReachabilityDetails -from google.cloud.network_management_v1.types.reachability import CreateConnectivityTestRequest -from google.cloud.network_management_v1.types.reachability import DeleteConnectivityTestRequest -from google.cloud.network_management_v1.types.reachability import GetConnectivityTestRequest -from google.cloud.network_management_v1.types.reachability import ListConnectivityTestsRequest -from google.cloud.network_management_v1.types.reachability import ListConnectivityTestsResponse -from google.cloud.network_management_v1.types.reachability import OperationMetadata -from google.cloud.network_management_v1.types.reachability import RerunConnectivityTestRequest -from google.cloud.network_management_v1.types.reachability import UpdateConnectivityTestRequest -from google.cloud.network_management_v1.types.trace import AbortInfo -from google.cloud.network_management_v1.types.trace import AppEngineVersionInfo -from google.cloud.network_management_v1.types.trace import CloudFunctionInfo -from google.cloud.network_management_v1.types.trace import CloudRunRevisionInfo -from google.cloud.network_management_v1.types.trace import CloudSQLInstanceInfo -from google.cloud.network_management_v1.types.trace import DeliverInfo -from google.cloud.network_management_v1.types.trace import DropInfo -from google.cloud.network_management_v1.types.trace import EndpointInfo -from google.cloud.network_management_v1.types.trace import FirewallInfo -from google.cloud.network_management_v1.types.trace import ForwardInfo -from google.cloud.network_management_v1.types.trace import ForwardingRuleInfo -from google.cloud.network_management_v1.types.trace import GKEMasterInfo -from google.cloud.network_management_v1.types.trace import GoogleServiceInfo -from google.cloud.network_management_v1.types.trace import InstanceInfo -from google.cloud.network_management_v1.types.trace import LoadBalancerBackend -from google.cloud.network_management_v1.types.trace import LoadBalancerBackendInfo -from google.cloud.network_management_v1.types.trace import LoadBalancerInfo -from google.cloud.network_management_v1.types.trace import NatInfo -from google.cloud.network_management_v1.types.trace import NetworkInfo -from google.cloud.network_management_v1.types.trace import ProxyConnectionInfo -from google.cloud.network_management_v1.types.trace import RedisClusterInfo -from google.cloud.network_management_v1.types.trace import RedisInstanceInfo -from google.cloud.network_management_v1.types.trace import RouteInfo -from google.cloud.network_management_v1.types.trace import ServerlessNegInfo -from google.cloud.network_management_v1.types.trace import Step -from google.cloud.network_management_v1.types.trace import StorageBucketInfo -from google.cloud.network_management_v1.types.trace import Trace -from google.cloud.network_management_v1.types.trace import VpcConnectorInfo -from google.cloud.network_management_v1.types.trace import VpnGatewayInfo -from google.cloud.network_management_v1.types.trace import VpnTunnelInfo -from google.cloud.network_management_v1.types.trace import LoadBalancerType - -__all__ = ('ReachabilityServiceClient', - 'ReachabilityServiceAsyncClient', - 'ConnectivityTest', - 'Endpoint', - 'LatencyDistribution', - 'LatencyPercentile', - 'ProbingDetails', - 'ReachabilityDetails', - 'CreateConnectivityTestRequest', - 'DeleteConnectivityTestRequest', - 'GetConnectivityTestRequest', - 'ListConnectivityTestsRequest', - 'ListConnectivityTestsResponse', - 'OperationMetadata', - 'RerunConnectivityTestRequest', - 'UpdateConnectivityTestRequest', - 'AbortInfo', - 'AppEngineVersionInfo', - 'CloudFunctionInfo', - 'CloudRunRevisionInfo', - 'CloudSQLInstanceInfo', - 'DeliverInfo', - 'DropInfo', - 'EndpointInfo', - 'FirewallInfo', - 'ForwardInfo', - 'ForwardingRuleInfo', - 'GKEMasterInfo', - 'GoogleServiceInfo', - 'InstanceInfo', - 'LoadBalancerBackend', - 'LoadBalancerBackendInfo', - 'LoadBalancerInfo', - 'NatInfo', - 'NetworkInfo', - 'ProxyConnectionInfo', - 'RedisClusterInfo', - 'RedisInstanceInfo', - 'RouteInfo', - 'ServerlessNegInfo', - 'Step', - 'StorageBucketInfo', - 'Trace', - 'VpcConnectorInfo', - 'VpnGatewayInfo', - 'VpnTunnelInfo', - 'LoadBalancerType', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/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-network-management/v1/google/cloud/network_management/py.typed b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed deleted file mode 100644 index 5aa063ef7ba9..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-management package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py deleted file mode 100644 index a55edfec563a..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py +++ /dev/null @@ -1,118 +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.network_management_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.reachability_service import ReachabilityServiceClient -from .services.reachability_service import ReachabilityServiceAsyncClient - -from .types.connectivity_test import ConnectivityTest -from .types.connectivity_test import Endpoint -from .types.connectivity_test import LatencyDistribution -from .types.connectivity_test import LatencyPercentile -from .types.connectivity_test import ProbingDetails -from .types.connectivity_test import ReachabilityDetails -from .types.reachability import CreateConnectivityTestRequest -from .types.reachability import DeleteConnectivityTestRequest -from .types.reachability import GetConnectivityTestRequest -from .types.reachability import ListConnectivityTestsRequest -from .types.reachability import ListConnectivityTestsResponse -from .types.reachability import OperationMetadata -from .types.reachability import RerunConnectivityTestRequest -from .types.reachability import UpdateConnectivityTestRequest -from .types.trace import AbortInfo -from .types.trace import AppEngineVersionInfo -from .types.trace import CloudFunctionInfo -from .types.trace import CloudRunRevisionInfo -from .types.trace import CloudSQLInstanceInfo -from .types.trace import DeliverInfo -from .types.trace import DropInfo -from .types.trace import EndpointInfo -from .types.trace import FirewallInfo -from .types.trace import ForwardInfo -from .types.trace import ForwardingRuleInfo -from .types.trace import GKEMasterInfo -from .types.trace import GoogleServiceInfo -from .types.trace import InstanceInfo -from .types.trace import LoadBalancerBackend -from .types.trace import LoadBalancerBackendInfo -from .types.trace import LoadBalancerInfo -from .types.trace import NatInfo -from .types.trace import NetworkInfo -from .types.trace import ProxyConnectionInfo -from .types.trace import RedisClusterInfo -from .types.trace import RedisInstanceInfo -from .types.trace import RouteInfo -from .types.trace import ServerlessNegInfo -from .types.trace import Step -from .types.trace import StorageBucketInfo -from .types.trace import Trace -from .types.trace import VpcConnectorInfo -from .types.trace import VpnGatewayInfo -from .types.trace import VpnTunnelInfo -from .types.trace import LoadBalancerType - -__all__ = ( - 'ReachabilityServiceAsyncClient', -'AbortInfo', -'AppEngineVersionInfo', -'CloudFunctionInfo', -'CloudRunRevisionInfo', -'CloudSQLInstanceInfo', -'ConnectivityTest', -'CreateConnectivityTestRequest', -'DeleteConnectivityTestRequest', -'DeliverInfo', -'DropInfo', -'Endpoint', -'EndpointInfo', -'FirewallInfo', -'ForwardInfo', -'ForwardingRuleInfo', -'GKEMasterInfo', -'GetConnectivityTestRequest', -'GoogleServiceInfo', -'InstanceInfo', -'LatencyDistribution', -'LatencyPercentile', -'ListConnectivityTestsRequest', -'ListConnectivityTestsResponse', -'LoadBalancerBackend', -'LoadBalancerBackendInfo', -'LoadBalancerInfo', -'LoadBalancerType', -'NatInfo', -'NetworkInfo', -'OperationMetadata', -'ProbingDetails', -'ProxyConnectionInfo', -'ReachabilityDetails', -'ReachabilityServiceClient', -'RedisClusterInfo', -'RedisInstanceInfo', -'RerunConnectivityTestRequest', -'RouteInfo', -'ServerlessNegInfo', -'Step', -'StorageBucketInfo', -'Trace', -'UpdateConnectivityTestRequest', -'VpcConnectorInfo', -'VpnGatewayInfo', -'VpnTunnelInfo', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json deleted file mode 100644 index 6c5315440fef..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json +++ /dev/null @@ -1,118 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.network_management_v1", - "protoPackage": "google.cloud.networkmanagement.v1", - "schema": "1.0", - "services": { - "ReachabilityService": { - "clients": { - "grpc": { - "libraryClient": "ReachabilityServiceClient", - "rpcs": { - "CreateConnectivityTest": { - "methods": [ - "create_connectivity_test" - ] - }, - "DeleteConnectivityTest": { - "methods": [ - "delete_connectivity_test" - ] - }, - "GetConnectivityTest": { - "methods": [ - "get_connectivity_test" - ] - }, - "ListConnectivityTests": { - "methods": [ - "list_connectivity_tests" - ] - }, - "RerunConnectivityTest": { - "methods": [ - "rerun_connectivity_test" - ] - }, - "UpdateConnectivityTest": { - "methods": [ - "update_connectivity_test" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ReachabilityServiceAsyncClient", - "rpcs": { - "CreateConnectivityTest": { - "methods": [ - "create_connectivity_test" - ] - }, - "DeleteConnectivityTest": { - "methods": [ - "delete_connectivity_test" - ] - }, - "GetConnectivityTest": { - "methods": [ - "get_connectivity_test" - ] - }, - "ListConnectivityTests": { - "methods": [ - "list_connectivity_tests" - ] - }, - "RerunConnectivityTest": { - "methods": [ - "rerun_connectivity_test" - ] - }, - "UpdateConnectivityTest": { - "methods": [ - "update_connectivity_test" - ] - } - } - }, - "rest": { - "libraryClient": "ReachabilityServiceClient", - "rpcs": { - "CreateConnectivityTest": { - "methods": [ - "create_connectivity_test" - ] - }, - "DeleteConnectivityTest": { - "methods": [ - "delete_connectivity_test" - ] - }, - "GetConnectivityTest": { - "methods": [ - "get_connectivity_test" - ] - }, - "ListConnectivityTests": { - "methods": [ - "list_connectivity_tests" - ] - }, - "RerunConnectivityTest": { - "methods": [ - "rerun_connectivity_test" - ] - }, - "UpdateConnectivityTest": { - "methods": [ - "update_connectivity_test" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_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-network-management/v1/google/cloud/network_management_v1/py.typed b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed deleted file mode 100644 index 5aa063ef7ba9..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-management package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_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-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py deleted file mode 100644 index 6f536eeb4ca5..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__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 ReachabilityServiceClient -from .async_client import ReachabilityServiceAsyncClient - -__all__ = ( - 'ReachabilityServiceClient', - 'ReachabilityServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py deleted file mode 100644 index 0ae89e6c03d8..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py +++ /dev/null @@ -1,1597 +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.network_management_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.location import locations_pb2 # type: ignore -from google.cloud.network_management_v1.services.reachability_service import pagers -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport -from .client import ReachabilityServiceClient - - -class ReachabilityServiceAsyncClient: - """The Reachability service in the Google Cloud Network - Management API provides services that analyze the reachability - within a single Google Virtual Private Cloud (VPC) network, - between peered VPC networks, between VPC and on-premises - networks, or between VPC networks and internet hosts. A - reachability analysis is based on Google Cloud network - configurations. - - You can use the analysis results to verify these configurations - and to troubleshoot connectivity issues. - """ - - _client: ReachabilityServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ReachabilityServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ReachabilityServiceClient._DEFAULT_UNIVERSE - - connectivity_test_path = staticmethod(ReachabilityServiceClient.connectivity_test_path) - parse_connectivity_test_path = staticmethod(ReachabilityServiceClient.parse_connectivity_test_path) - common_billing_account_path = staticmethod(ReachabilityServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ReachabilityServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ReachabilityServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ReachabilityServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ReachabilityServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ReachabilityServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ReachabilityServiceClient.common_project_path) - parse_common_project_path = staticmethod(ReachabilityServiceClient.parse_common_project_path) - common_location_path = staticmethod(ReachabilityServiceClient.common_location_path) - parse_common_location_path = staticmethod(ReachabilityServiceClient.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: - ReachabilityServiceAsyncClient: The constructed client. - """ - return ReachabilityServiceClient.from_service_account_info.__func__(ReachabilityServiceAsyncClient, 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: - ReachabilityServiceAsyncClient: The constructed client. - """ - return ReachabilityServiceClient.from_service_account_file.__func__(ReachabilityServiceAsyncClient, 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 ReachabilityServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ReachabilityServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ReachabilityServiceTransport: 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 = ReachabilityServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ReachabilityServiceTransport, Callable[..., ReachabilityServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the reachability service async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,ReachabilityServiceTransport,Callable[..., ReachabilityServiceTransport]]]): - 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 ReachabilityServiceTransport 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 = ReachabilityServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_connectivity_tests(self, - request: Optional[Union[reachability.ListConnectivityTestsRequest, 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.ListConnectivityTestsAsyncPager: - r"""Lists all Connectivity Tests owned by a project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_list_connectivity_tests(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.ListConnectivityTestsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_connectivity_tests(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.ListConnectivityTestsRequest, dict]]): - The request object. Request for the ``ListConnectivityTests`` method. - parent (:class:`str`): - Required. The parent resource of the Connectivity Tests: - ``projects/{project_id}/locations/global`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsAsyncPager: - Response for the ListConnectivityTests method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, reachability.ListConnectivityTestsRequest): - request = reachability.ListConnectivityTestsRequest(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_connectivity_tests] - - # 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.ListConnectivityTestsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_connectivity_test(self, - request: Optional[Union[reachability.GetConnectivityTestRequest, 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]] = (), - ) -> connectivity_test.ConnectivityTest: - r"""Gets the details of a specific Connectivity Test. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_get_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.GetConnectivityTestRequest( - name="name_value", - ) - - # Make the request - response = await client.get_connectivity_test(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.GetConnectivityTestRequest, dict]]): - The request object. Request for the ``GetConnectivityTest`` method. - name (:class:`str`): - Required. ``ConnectivityTest`` resource name using the - form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - - 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.network_management_v1.types.ConnectivityTest: - A Connectivity Test for a network - reachability analysis. - - """ - # Create or coerce a 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, reachability.GetConnectivityTestRequest): - request = reachability.GetConnectivityTestRequest(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_connectivity_test] - - # 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_connectivity_test(self, - request: Optional[Union[reachability.CreateConnectivityTestRequest, dict]] = None, - *, - parent: Optional[str] = None, - test_id: Optional[str] = None, - resource: Optional[connectivity_test.ConnectivityTest] = 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 Connectivity Test. After you create a test, the - reachability analysis is performed as part of the long running - operation, which completes when the analysis completes. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, containing non-existent resources in the - network, or you don't have read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - AMBIGUOUS. For more information, see the Connectivity Test - documentation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_create_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.CreateConnectivityTestRequest( - parent="parent_value", - test_id="test_id_value", - ) - - # Make the request - operation = client.create_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.CreateConnectivityTestRequest, dict]]): - The request object. Request for the ``CreateConnectivityTest`` method. - parent (:class:`str`): - Required. The parent resource of the Connectivity Test - to create: ``projects/{project_id}/locations/global`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - test_id (:class:`str`): - Required. The logical name of the Connectivity Test in - your project with the following restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-40 characters. - - Must end with a number or a letter. - - Must be unique within the customer project - - This corresponds to the ``test_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (:class:`google.cloud.network_management_v1.types.ConnectivityTest`): - Required. A ``ConnectivityTest`` resource - This corresponds to the ``resource`` 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.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a 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, test_id, resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.CreateConnectivityTestRequest): - request = reachability.CreateConnectivityTestRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if test_id is not None: - request.test_id = test_id - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_connectivity_test] - - # 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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_connectivity_test(self, - request: Optional[Union[reachability.UpdateConnectivityTestRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - resource: Optional[connectivity_test.ConnectivityTest] = 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 configuration of an existing ``ConnectivityTest``. - After you update a test, the reachability analysis is performed - as part of the long running operation, which completes when the - analysis completes. The Reachability state in the test resource - is updated with the new result. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, they contain non-existent resources in the - network, or the user does not have read permissions to the - network configurations of listed projects), then the - reachability result returns a value of UNKNOWN. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for - more details. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_update_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.UpdateConnectivityTestRequest( - ) - - # Make the request - operation = client.update_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.UpdateConnectivityTestRequest, dict]]): - The request object. Request for the ``UpdateConnectivityTest`` method. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask of fields to update. - At least one path must be supplied in - this field. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (:class:`google.cloud.network_management_v1.types.ConnectivityTest`): - Required. Only fields specified in update_mask are - updated. - - This corresponds to the ``resource`` 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.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a 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([update_mask, resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.UpdateConnectivityTestRequest): - request = reachability.UpdateConnectivityTestRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if update_mask is not None: - request.update_mask = update_mask - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_connectivity_test] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource.name", request.resource.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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - async def rerun_connectivity_test(self, - request: Optional[Union[reachability.RerunConnectivityTestRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Rerun an existing ``ConnectivityTest``. After the user triggers - the rerun, the reachability analysis is performed as part of the - long running operation, which completes when the analysis - completes. - - Even though the test configuration remains the same, the - reachability result may change due to underlying network - configuration changes. - - If the endpoint specifications in ``ConnectivityTest`` become - invalid (for example, specified resources are deleted in the - network, or you lost read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_rerun_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.RerunConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.rerun_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.RerunConnectivityTestRequest, dict]]): - The request object. Request for the ``RerunConnectivityTest`` 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: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.RerunConnectivityTestRequest): - request = reachability.RerunConnectivityTestRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.rerun_connectivity_test] - - # 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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_connectivity_test(self, - request: Optional[Union[reachability.DeleteConnectivityTestRequest, 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 specific ``ConnectivityTest``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_delete_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.DeleteConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.DeleteConnectivityTestRequest, dict]]): - The request object. Request for the ``DeleteConnectivityTest`` method. - name (:class:`str`): - Required. Connectivity Test resource name using the - form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - - 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, reachability.DeleteConnectivityTestRequest): - request = reachability.DeleteConnectivityTestRequest(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_connectivity_test] - - # 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=reachability.OperationMetadata, - ) - - # 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, 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) -> "ReachabilityServiceAsyncClient": - 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__ = ( - "ReachabilityServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py deleted file mode 100644 index af1f94e73757..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py +++ /dev/null @@ -1,1917 +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.network_management_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.location import locations_pb2 # type: ignore -from google.cloud.network_management_v1.services.reachability_service import pagers -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ReachabilityServiceGrpcTransport -from .transports.grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport -from .transports.rest import ReachabilityServiceRestTransport - - -class ReachabilityServiceClientMeta(type): - """Metaclass for the ReachabilityService 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[ReachabilityServiceTransport]] - _transport_registry["grpc"] = ReachabilityServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ReachabilityServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ReachabilityServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ReachabilityServiceTransport]: - """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 ReachabilityServiceClient(metaclass=ReachabilityServiceClientMeta): - """The Reachability service in the Google Cloud Network - Management API provides services that analyze the reachability - within a single Google Virtual Private Cloud (VPC) network, - between peered VPC networks, between VPC and on-premises - networks, or between VPC networks and internet hosts. A - reachability analysis is based on Google Cloud network - configurations. - - You can use the analysis results to verify these configurations - and to troubleshoot connectivity issues. - """ - - @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 = "networkmanagement.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "networkmanagement.{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: - ReachabilityServiceClient: 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: - ReachabilityServiceClient: 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) -> ReachabilityServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ReachabilityServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def connectivity_test_path(project: str,test: str,) -> str: - """Returns a fully-qualified connectivity_test string.""" - return "projects/{project}/locations/global/connectivityTests/{test}".format(project=project, test=test, ) - - @staticmethod - def parse_connectivity_test_path(path: str) -> Dict[str,str]: - """Parses a connectivity_test path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/global/connectivityTests/(?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 = ReachabilityServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ReachabilityServiceClient._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 = ReachabilityServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ReachabilityServiceTransport, Callable[..., ReachabilityServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the reachability service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,ReachabilityServiceTransport,Callable[..., ReachabilityServiceTransport]]]): - 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 ReachabilityServiceTransport 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 = ReachabilityServiceClient._read_environment_variables() - self._client_cert_source = ReachabilityServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ReachabilityServiceClient._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, ReachabilityServiceTransport) - if transport_provided: - # transport is a ReachabilityServiceTransport 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(ReachabilityServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ReachabilityServiceClient._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[ReachabilityServiceTransport], Callable[..., ReachabilityServiceTransport]] = ( - ReachabilityServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ReachabilityServiceTransport], 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_connectivity_tests(self, - request: Optional[Union[reachability.ListConnectivityTestsRequest, 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.ListConnectivityTestsPager: - r"""Lists all Connectivity Tests owned by a project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_list_connectivity_tests(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.ListConnectivityTestsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_connectivity_tests(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.ListConnectivityTestsRequest, dict]): - The request object. Request for the ``ListConnectivityTests`` method. - parent (str): - Required. The parent resource of the Connectivity Tests: - ``projects/{project_id}/locations/global`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsPager: - Response for the ListConnectivityTests method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, reachability.ListConnectivityTestsRequest): - request = reachability.ListConnectivityTestsRequest(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_connectivity_tests] - - # 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.ListConnectivityTestsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_connectivity_test(self, - request: Optional[Union[reachability.GetConnectivityTestRequest, 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]] = (), - ) -> connectivity_test.ConnectivityTest: - r"""Gets the details of a specific Connectivity Test. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_get_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.GetConnectivityTestRequest( - name="name_value", - ) - - # Make the request - response = client.get_connectivity_test(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.GetConnectivityTestRequest, dict]): - The request object. Request for the ``GetConnectivityTest`` method. - name (str): - Required. ``ConnectivityTest`` resource name using the - form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - - 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.network_management_v1.types.ConnectivityTest: - A Connectivity Test for a network - reachability analysis. - - """ - # Create or coerce a 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, reachability.GetConnectivityTestRequest): - request = reachability.GetConnectivityTestRequest(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_connectivity_test] - - # 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_connectivity_test(self, - request: Optional[Union[reachability.CreateConnectivityTestRequest, dict]] = None, - *, - parent: Optional[str] = None, - test_id: Optional[str] = None, - resource: Optional[connectivity_test.ConnectivityTest] = 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 Connectivity Test. After you create a test, the - reachability analysis is performed as part of the long running - operation, which completes when the analysis completes. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, containing non-existent resources in the - network, or you don't have read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - AMBIGUOUS. For more information, see the Connectivity Test - documentation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_create_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.CreateConnectivityTestRequest( - parent="parent_value", - test_id="test_id_value", - ) - - # Make the request - operation = client.create_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.CreateConnectivityTestRequest, dict]): - The request object. Request for the ``CreateConnectivityTest`` method. - parent (str): - Required. The parent resource of the Connectivity Test - to create: ``projects/{project_id}/locations/global`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - test_id (str): - Required. The logical name of the Connectivity Test in - your project with the following restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-40 characters. - - Must end with a number or a letter. - - Must be unique within the customer project - - This corresponds to the ``test_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (google.cloud.network_management_v1.types.ConnectivityTest): - Required. A ``ConnectivityTest`` resource - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a 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, test_id, resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.CreateConnectivityTestRequest): - request = reachability.CreateConnectivityTestRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if test_id is not None: - request.test_id = test_id - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_connectivity_test] - - # 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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_connectivity_test(self, - request: Optional[Union[reachability.UpdateConnectivityTestRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - resource: Optional[connectivity_test.ConnectivityTest] = 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 configuration of an existing ``ConnectivityTest``. - After you update a test, the reachability analysis is performed - as part of the long running operation, which completes when the - analysis completes. The Reachability state in the test resource - is updated with the new result. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, they contain non-existent resources in the - network, or the user does not have read permissions to the - network configurations of listed projects), then the - reachability result returns a value of UNKNOWN. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for - more details. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_update_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.UpdateConnectivityTestRequest( - ) - - # Make the request - operation = client.update_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.UpdateConnectivityTestRequest, dict]): - The request object. Request for the ``UpdateConnectivityTest`` method. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask of fields to update. - At least one path must be supplied in - this field. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (google.cloud.network_management_v1.types.ConnectivityTest): - Required. Only fields specified in update_mask are - updated. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a 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([update_mask, resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.UpdateConnectivityTestRequest): - request = reachability.UpdateConnectivityTestRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if update_mask is not None: - request.update_mask = update_mask - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_connectivity_test] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource.name", request.resource.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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - def rerun_connectivity_test(self, - request: Optional[Union[reachability.RerunConnectivityTestRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Rerun an existing ``ConnectivityTest``. After the user triggers - the rerun, the reachability analysis is performed as part of the - long running operation, which completes when the analysis - completes. - - Even though the test configuration remains the same, the - reachability result may change due to underlying network - configuration changes. - - If the endpoint specifications in ``ConnectivityTest`` become - invalid (for example, specified resources are deleted in the - network, or you lost read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_rerun_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.RerunConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.rerun_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.RerunConnectivityTestRequest, dict]): - The request object. Request for the ``RerunConnectivityTest`` 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: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.RerunConnectivityTestRequest): - request = reachability.RerunConnectivityTestRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rerun_connectivity_test] - - # 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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_connectivity_test(self, - request: Optional[Union[reachability.DeleteConnectivityTestRequest, 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 specific ``ConnectivityTest``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_delete_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.DeleteConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.DeleteConnectivityTestRequest, dict]): - The request object. Request for the ``DeleteConnectivityTest`` method. - name (str): - Required. Connectivity Test resource name using the - form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - - 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, reachability.DeleteConnectivityTestRequest): - request = reachability.DeleteConnectivityTestRequest(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_connectivity_test] - - # 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=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ReachabilityServiceClient": - 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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__ = ( - "ReachabilityServiceClient", -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py deleted file mode 100644 index 99e5a56eabf4..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py +++ /dev/null @@ -1,163 +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.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability - - -class ListConnectivityTestsPager: - """A pager for iterating through ``list_connectivity_tests`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``resources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConnectivityTests`` requests and continue to iterate - through the ``resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` - 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[..., reachability.ListConnectivityTestsResponse], - request: reachability.ListConnectivityTestsRequest, - response: reachability.ListConnectivityTestsResponse, - *, - 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.network_management_v1.types.ListConnectivityTestsRequest): - The initial request object. - response (google.cloud.network_management_v1.types.ListConnectivityTestsResponse): - 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 = reachability.ListConnectivityTestsRequest(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[reachability.ListConnectivityTestsResponse]: - 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[connectivity_test.ConnectivityTest]: - for page in self.pages: - yield from page.resources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConnectivityTestsAsyncPager: - """A pager for iterating through ``list_connectivity_tests`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``resources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConnectivityTests`` requests and continue to iterate - through the ``resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` - 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[reachability.ListConnectivityTestsResponse]], - request: reachability.ListConnectivityTestsRequest, - response: reachability.ListConnectivityTestsResponse, - *, - 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.network_management_v1.types.ListConnectivityTestsRequest): - The initial request object. - response (google.cloud.network_management_v1.types.ListConnectivityTestsResponse): - 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 = reachability.ListConnectivityTestsRequest(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[reachability.ListConnectivityTestsResponse]: - 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[connectivity_test.ConnectivityTest]: - async def async_generator(): - async for page in self.pages: - for response in page.resources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst deleted file mode 100644 index b6e73840492e..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ReachabilityServiceTransport` is the ABC for all transports. -- public child `ReachabilityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ReachabilityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseReachabilityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ReachabilityServiceRestTransport` 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-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py deleted file mode 100644 index e03fcb9eb663..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/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 ReachabilityServiceTransport -from .grpc import ReachabilityServiceGrpcTransport -from .grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport -from .rest import ReachabilityServiceRestTransport -from .rest import ReachabilityServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ReachabilityServiceTransport]] -_transport_registry['grpc'] = ReachabilityServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ReachabilityServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ReachabilityServiceRestTransport - -__all__ = ( - 'ReachabilityServiceTransport', - 'ReachabilityServiceGrpcTransport', - 'ReachabilityServiceGrpcAsyncIOTransport', - 'ReachabilityServiceRestTransport', - 'ReachabilityServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py deleted file mode 100644 index 3d64ec294ab6..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py +++ /dev/null @@ -1,362 +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.network_management_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.location import locations_pb2 # type: ignore -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ReachabilityServiceTransport(abc.ABC): - """Abstract transport class for ReachabilityService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'networkmanagement.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: 'networkmanagement.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_connectivity_tests: gapic_v1.method.wrap_method( - self.list_connectivity_tests, - default_timeout=None, - client_info=client_info, - ), - self.get_connectivity_test: gapic_v1.method.wrap_method( - self.get_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.create_connectivity_test: gapic_v1.method.wrap_method( - self.create_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.update_connectivity_test: gapic_v1.method.wrap_method( - self.update_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.rerun_connectivity_test: gapic_v1.method.wrap_method( - self.rerun_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.delete_connectivity_test: gapic_v1.method.wrap_method( - self.delete_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_connectivity_tests(self) -> Callable[ - [reachability.ListConnectivityTestsRequest], - Union[ - reachability.ListConnectivityTestsResponse, - Awaitable[reachability.ListConnectivityTestsResponse] - ]]: - raise NotImplementedError() - - @property - def get_connectivity_test(self) -> Callable[ - [reachability.GetConnectivityTestRequest], - Union[ - connectivity_test.ConnectivityTest, - Awaitable[connectivity_test.ConnectivityTest] - ]]: - raise NotImplementedError() - - @property - def create_connectivity_test(self) -> Callable[ - [reachability.CreateConnectivityTestRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_connectivity_test(self) -> Callable[ - [reachability.UpdateConnectivityTestRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rerun_connectivity_test(self) -> Callable[ - [reachability.RerunConnectivityTestRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_connectivity_test(self) -> Callable[ - [reachability.DeleteConnectivityTestRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ReachabilityServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py deleted file mode 100644 index 04909d6e22c7..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py +++ /dev/null @@ -1,660 +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.location import locations_pb2 # type: ignore -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO - - -class ReachabilityServiceGrpcTransport(ReachabilityServiceTransport): - """gRPC backend transport for ReachabilityService. - - The Reachability service in the Google Cloud Network - Management API provides services that analyze the reachability - within a single Google Virtual Private Cloud (VPC) network, - between peered VPC networks, between VPC and on-premises - networks, or between VPC networks and internet hosts. A - reachability analysis is based on Google Cloud network - configurations. - - You can use the analysis results to verify these configurations - and to troubleshoot connectivity issues. - - 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 = 'networkmanagement.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: 'networkmanagement.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 = 'networkmanagement.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_connectivity_tests(self) -> Callable[ - [reachability.ListConnectivityTestsRequest], - reachability.ListConnectivityTestsResponse]: - r"""Return a callable for the list connectivity tests method over gRPC. - - Lists all Connectivity Tests owned by a project. - - Returns: - Callable[[~.ListConnectivityTestsRequest], - ~.ListConnectivityTestsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_connectivity_tests' not in self._stubs: - self._stubs['list_connectivity_tests'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/ListConnectivityTests', - request_serializer=reachability.ListConnectivityTestsRequest.serialize, - response_deserializer=reachability.ListConnectivityTestsResponse.deserialize, - ) - return self._stubs['list_connectivity_tests'] - - @property - def get_connectivity_test(self) -> Callable[ - [reachability.GetConnectivityTestRequest], - connectivity_test.ConnectivityTest]: - r"""Return a callable for the get connectivity test method over gRPC. - - Gets the details of a specific Connectivity Test. - - Returns: - Callable[[~.GetConnectivityTestRequest], - ~.ConnectivityTest]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_connectivity_test' not in self._stubs: - self._stubs['get_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/GetConnectivityTest', - request_serializer=reachability.GetConnectivityTestRequest.serialize, - response_deserializer=connectivity_test.ConnectivityTest.deserialize, - ) - return self._stubs['get_connectivity_test'] - - @property - def create_connectivity_test(self) -> Callable[ - [reachability.CreateConnectivityTestRequest], - operations_pb2.Operation]: - r"""Return a callable for the create connectivity test method over gRPC. - - Creates a new Connectivity Test. After you create a test, the - reachability analysis is performed as part of the long running - operation, which completes when the analysis completes. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, containing non-existent resources in the - network, or you don't have read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - AMBIGUOUS. For more information, see the Connectivity Test - documentation. - - Returns: - Callable[[~.CreateConnectivityTestRequest], - ~.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_connectivity_test' not in self._stubs: - self._stubs['create_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/CreateConnectivityTest', - request_serializer=reachability.CreateConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_connectivity_test'] - - @property - def update_connectivity_test(self) -> Callable[ - [reachability.UpdateConnectivityTestRequest], - operations_pb2.Operation]: - r"""Return a callable for the update connectivity test method over gRPC. - - Updates the configuration of an existing ``ConnectivityTest``. - After you update a test, the reachability analysis is performed - as part of the long running operation, which completes when the - analysis completes. The Reachability state in the test resource - is updated with the new result. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, they contain non-existent resources in the - network, or the user does not have read permissions to the - network configurations of listed projects), then the - reachability result returns a value of UNKNOWN. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for - more details. - - Returns: - Callable[[~.UpdateConnectivityTestRequest], - ~.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_connectivity_test' not in self._stubs: - self._stubs['update_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/UpdateConnectivityTest', - request_serializer=reachability.UpdateConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_connectivity_test'] - - @property - def rerun_connectivity_test(self) -> Callable[ - [reachability.RerunConnectivityTestRequest], - operations_pb2.Operation]: - r"""Return a callable for the rerun connectivity test method over gRPC. - - Rerun an existing ``ConnectivityTest``. After the user triggers - the rerun, the reachability analysis is performed as part of the - long running operation, which completes when the analysis - completes. - - Even though the test configuration remains the same, the - reachability result may change due to underlying network - configuration changes. - - If the endpoint specifications in ``ConnectivityTest`` become - invalid (for example, specified resources are deleted in the - network, or you lost read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - Returns: - Callable[[~.RerunConnectivityTestRequest], - ~.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 'rerun_connectivity_test' not in self._stubs: - self._stubs['rerun_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/RerunConnectivityTest', - request_serializer=reachability.RerunConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rerun_connectivity_test'] - - @property - def delete_connectivity_test(self) -> Callable[ - [reachability.DeleteConnectivityTestRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete connectivity test method over gRPC. - - Deletes a specific ``ConnectivityTest``. - - Returns: - Callable[[~.DeleteConnectivityTestRequest], - ~.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_connectivity_test' not in self._stubs: - self._stubs['delete_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/DeleteConnectivityTest', - request_serializer=reachability.DeleteConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_connectivity_test'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ReachabilityServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py deleted file mode 100644 index 15d349b57214..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,751 +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.location import locations_pb2 # type: ignore -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ReachabilityServiceGrpcTransport - - -class ReachabilityServiceGrpcAsyncIOTransport(ReachabilityServiceTransport): - """gRPC AsyncIO backend transport for ReachabilityService. - - The Reachability service in the Google Cloud Network - Management API provides services that analyze the reachability - within a single Google Virtual Private Cloud (VPC) network, - between peered VPC networks, between VPC and on-premises - networks, or between VPC networks and internet hosts. A - reachability analysis is based on Google Cloud network - configurations. - - You can use the analysis results to verify these configurations - and to troubleshoot connectivity issues. - - 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 = 'networkmanagement.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 = 'networkmanagement.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: 'networkmanagement.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_connectivity_tests(self) -> Callable[ - [reachability.ListConnectivityTestsRequest], - Awaitable[reachability.ListConnectivityTestsResponse]]: - r"""Return a callable for the list connectivity tests method over gRPC. - - Lists all Connectivity Tests owned by a project. - - Returns: - Callable[[~.ListConnectivityTestsRequest], - Awaitable[~.ListConnectivityTestsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_connectivity_tests' not in self._stubs: - self._stubs['list_connectivity_tests'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/ListConnectivityTests', - request_serializer=reachability.ListConnectivityTestsRequest.serialize, - response_deserializer=reachability.ListConnectivityTestsResponse.deserialize, - ) - return self._stubs['list_connectivity_tests'] - - @property - def get_connectivity_test(self) -> Callable[ - [reachability.GetConnectivityTestRequest], - Awaitable[connectivity_test.ConnectivityTest]]: - r"""Return a callable for the get connectivity test method over gRPC. - - Gets the details of a specific Connectivity Test. - - Returns: - Callable[[~.GetConnectivityTestRequest], - Awaitable[~.ConnectivityTest]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_connectivity_test' not in self._stubs: - self._stubs['get_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/GetConnectivityTest', - request_serializer=reachability.GetConnectivityTestRequest.serialize, - response_deserializer=connectivity_test.ConnectivityTest.deserialize, - ) - return self._stubs['get_connectivity_test'] - - @property - def create_connectivity_test(self) -> Callable[ - [reachability.CreateConnectivityTestRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create connectivity test method over gRPC. - - Creates a new Connectivity Test. After you create a test, the - reachability analysis is performed as part of the long running - operation, which completes when the analysis completes. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, containing non-existent resources in the - network, or you don't have read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - AMBIGUOUS. For more information, see the Connectivity Test - documentation. - - Returns: - Callable[[~.CreateConnectivityTestRequest], - 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_connectivity_test' not in self._stubs: - self._stubs['create_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/CreateConnectivityTest', - request_serializer=reachability.CreateConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_connectivity_test'] - - @property - def update_connectivity_test(self) -> Callable[ - [reachability.UpdateConnectivityTestRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update connectivity test method over gRPC. - - Updates the configuration of an existing ``ConnectivityTest``. - After you update a test, the reachability analysis is performed - as part of the long running operation, which completes when the - analysis completes. The Reachability state in the test resource - is updated with the new result. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, they contain non-existent resources in the - network, or the user does not have read permissions to the - network configurations of listed projects), then the - reachability result returns a value of UNKNOWN. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for - more details. - - Returns: - Callable[[~.UpdateConnectivityTestRequest], - 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_connectivity_test' not in self._stubs: - self._stubs['update_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/UpdateConnectivityTest', - request_serializer=reachability.UpdateConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_connectivity_test'] - - @property - def rerun_connectivity_test(self) -> Callable[ - [reachability.RerunConnectivityTestRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rerun connectivity test method over gRPC. - - Rerun an existing ``ConnectivityTest``. After the user triggers - the rerun, the reachability analysis is performed as part of the - long running operation, which completes when the analysis - completes. - - Even though the test configuration remains the same, the - reachability result may change due to underlying network - configuration changes. - - If the endpoint specifications in ``ConnectivityTest`` become - invalid (for example, specified resources are deleted in the - network, or you lost read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - Returns: - Callable[[~.RerunConnectivityTestRequest], - 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 'rerun_connectivity_test' not in self._stubs: - self._stubs['rerun_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/RerunConnectivityTest', - request_serializer=reachability.RerunConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rerun_connectivity_test'] - - @property - def delete_connectivity_test(self) -> Callable[ - [reachability.DeleteConnectivityTestRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete connectivity test method over gRPC. - - Deletes a specific ``ConnectivityTest``. - - Returns: - Callable[[~.DeleteConnectivityTestRequest], - 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_connectivity_test' not in self._stubs: - self._stubs['delete_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/DeleteConnectivityTest', - request_serializer=reachability.DeleteConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_connectivity_test'] - - 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_connectivity_tests: self._wrap_method( - self.list_connectivity_tests, - default_timeout=None, - client_info=client_info, - ), - self.get_connectivity_test: self._wrap_method( - self.get_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.create_connectivity_test: self._wrap_method( - self.create_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.update_connectivity_test: self._wrap_method( - self.update_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.rerun_connectivity_test: self._wrap_method( - self.rerun_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.delete_connectivity_test: self._wrap_method( - self.delete_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self.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"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'ReachabilityServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py deleted file mode 100644 index aa84d74c181c..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py +++ /dev/null @@ -1,1714 +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.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseReachabilityServiceRestTransport -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 ReachabilityServiceRestInterceptor: - """Interceptor for ReachabilityService. - - 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 ReachabilityServiceRestTransport. - - .. code-block:: python - class MyCustomReachabilityServiceInterceptor(ReachabilityServiceRestInterceptor): - def pre_create_connectivity_test(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_connectivity_test(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_connectivity_test(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_connectivity_test(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_connectivity_test(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_connectivity_test(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_connectivity_tests(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_connectivity_tests(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_rerun_connectivity_test(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_rerun_connectivity_test(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_connectivity_test(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_connectivity_test(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ReachabilityServiceRestTransport(interceptor=MyCustomReachabilityServiceInterceptor()) - client = ReachabilityServiceClient(transport=transport) - - - """ - def pre_create_connectivity_test(self, request: reachability.CreateConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.CreateConnectivityTestRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_connectivity_test - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_create_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_connectivity_test - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_delete_connectivity_test(self, request: reachability.DeleteConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.DeleteConnectivityTestRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_connectivity_test - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_delete_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_connectivity_test - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_get_connectivity_test(self, request: reachability.GetConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.GetConnectivityTestRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_connectivity_test - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_get_connectivity_test(self, response: connectivity_test.ConnectivityTest) -> connectivity_test.ConnectivityTest: - """Post-rpc interceptor for get_connectivity_test - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_list_connectivity_tests(self, request: reachability.ListConnectivityTestsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.ListConnectivityTestsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_connectivity_tests - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_list_connectivity_tests(self, response: reachability.ListConnectivityTestsResponse) -> reachability.ListConnectivityTestsResponse: - """Post-rpc interceptor for list_connectivity_tests - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_rerun_connectivity_test(self, request: reachability.RerunConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.RerunConnectivityTestRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for rerun_connectivity_test - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_rerun_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for rerun_connectivity_test - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_update_connectivity_test(self, request: reachability.UpdateConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.UpdateConnectivityTestRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_connectivity_test - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_update_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_connectivity_test - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ReachabilityServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ReachabilityServiceRestInterceptor - - -class ReachabilityServiceRestTransport(_BaseReachabilityServiceRestTransport): - """REST backend synchronous transport for ReachabilityService. - - The Reachability service in the Google Cloud Network - Management API provides services that analyze the reachability - within a single Google Virtual Private Cloud (VPC) network, - between peered VPC networks, between VPC and on-premises - networks, or between VPC networks and internet hosts. A - reachability analysis is based on Google Cloud network - configurations. - - You can use the analysis results to verify these configurations - and to troubleshoot connectivity issues. - - 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 = 'networkmanagement.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[ReachabilityServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networkmanagement.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 ReachabilityServiceRestInterceptor() - 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/global/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/global/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/global/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/global}/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 _CreateConnectivityTest(_BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.CreateConnectivityTest") - - @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: reachability.CreateConnectivityTestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create connectivity test method over HTTP. - - Args: - request (~.reachability.CreateConnectivityTestRequest): - The request object. Request for the ``CreateConnectivityTest`` 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: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_http_options() - request, metadata = self._interceptor.pre_create_connectivity_test(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._CreateConnectivityTest._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_connectivity_test(resp) - return resp - - class _DeleteConnectivityTest(_BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.DeleteConnectivityTest") - - @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: reachability.DeleteConnectivityTestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete connectivity test method over HTTP. - - Args: - request (~.reachability.DeleteConnectivityTestRequest): - The request object. Request for the ``DeleteConnectivityTest`` 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: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_http_options() - request, metadata = self._interceptor.pre_delete_connectivity_test(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._DeleteConnectivityTest._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_connectivity_test(resp) - return resp - - class _GetConnectivityTest(_BaseReachabilityServiceRestTransport._BaseGetConnectivityTest, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.GetConnectivityTest") - - @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: reachability.GetConnectivityTestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> connectivity_test.ConnectivityTest: - r"""Call the get connectivity test method over HTTP. - - Args: - request (~.reachability.GetConnectivityTestRequest): - The request object. Request for the ``GetConnectivityTest`` 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: - ~.connectivity_test.ConnectivityTest: - A Connectivity Test for a network - reachability analysis. - - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_http_options() - request, metadata = self._interceptor.pre_get_connectivity_test(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._GetConnectivityTest._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 = connectivity_test.ConnectivityTest() - pb_resp = connectivity_test.ConnectivityTest.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_connectivity_test(resp) - return resp - - class _ListConnectivityTests(_BaseReachabilityServiceRestTransport._BaseListConnectivityTests, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.ListConnectivityTests") - - @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: reachability.ListConnectivityTestsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> reachability.ListConnectivityTestsResponse: - r"""Call the list connectivity tests method over HTTP. - - Args: - request (~.reachability.ListConnectivityTestsRequest): - The request object. Request for the ``ListConnectivityTests`` 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: - ~.reachability.ListConnectivityTestsResponse: - Response for the ``ListConnectivityTests`` method. - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_http_options() - request, metadata = self._interceptor.pre_list_connectivity_tests(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._ListConnectivityTests._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 = reachability.ListConnectivityTestsResponse() - pb_resp = reachability.ListConnectivityTestsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_connectivity_tests(resp) - return resp - - class _RerunConnectivityTest(_BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.RerunConnectivityTest") - - @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: reachability.RerunConnectivityTestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the rerun connectivity test method over HTTP. - - Args: - request (~.reachability.RerunConnectivityTestRequest): - The request object. Request for the ``RerunConnectivityTest`` 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: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_http_options() - request, metadata = self._interceptor.pre_rerun_connectivity_test(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._RerunConnectivityTest._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_rerun_connectivity_test(resp) - return resp - - class _UpdateConnectivityTest(_BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.UpdateConnectivityTest") - - @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: reachability.UpdateConnectivityTestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update connectivity test method over HTTP. - - Args: - request (~.reachability.UpdateConnectivityTestRequest): - The request object. Request for the ``UpdateConnectivityTest`` 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: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_http_options() - request, metadata = self._interceptor.pre_update_connectivity_test(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._UpdateConnectivityTest._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_connectivity_test(resp) - return resp - - @property - def create_connectivity_test(self) -> Callable[ - [reachability.CreateConnectivityTestRequest], - 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._CreateConnectivityTest(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_connectivity_test(self) -> Callable[ - [reachability.DeleteConnectivityTestRequest], - 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._DeleteConnectivityTest(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_connectivity_test(self) -> Callable[ - [reachability.GetConnectivityTestRequest], - connectivity_test.ConnectivityTest]: - # 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._GetConnectivityTest(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_connectivity_tests(self) -> Callable[ - [reachability.ListConnectivityTestsRequest], - reachability.ListConnectivityTestsResponse]: - # 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._ListConnectivityTests(self._session, self._host, self._interceptor) # type: ignore - - @property - def rerun_connectivity_test(self) -> Callable[ - [reachability.RerunConnectivityTestRequest], - 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._RerunConnectivityTest(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_connectivity_test(self) -> Callable[ - [reachability.UpdateConnectivityTestRequest], - 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._UpdateConnectivityTest(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(_BaseReachabilityServiceRestTransport._BaseGetLocation, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseListLocations, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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 get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseReachabilityServiceRestTransport._BaseGetIamPolicy, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseReachabilityServiceRestTransport._BaseSetIamPolicy, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseReachabilityServiceRestTransport._BaseTestIamPermissions, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseReachabilityServiceRestTransport._BaseCancelOperation, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_http_options() - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseDeleteOperation, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_http_options() - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseGetOperation, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseListOperations, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseListOperations._get_http_options() - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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__=( - 'ReachabilityServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py deleted file mode 100644 index 7dd2991844be..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py +++ /dev/null @@ -1,588 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseReachabilityServiceRestTransport(ReachabilityServiceTransport): - """Base REST backend transport for ReachabilityService. - - 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 = 'networkmanagement.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: 'networkmanagement.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 _BaseCreateConnectivityTest: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "testId" : "", } - - @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/global}/connectivityTests', - 'body': 'resource', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.CreateConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteConnectivityTest: - 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/global/connectivityTests/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.DeleteConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetConnectivityTest: - 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/global/connectivityTests/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.GetConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListConnectivityTests: - 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/global}/connectivityTests', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.ListConnectivityTestsRequest.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(_BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseRerunConnectivityTest: - 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/global/connectivityTests/*}:rerun', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.RerunConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateConnectivityTest: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{resource.name=projects/*/locations/global/connectivityTests/*}', - 'body': 'resource', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.UpdateConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLocation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListLocations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:getIamPolicy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseCancelOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/global/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/global/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/global/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/global}/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__=( - '_BaseReachabilityServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py deleted file mode 100644 index ce14d0c9af68..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_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 .connectivity_test import ( - ConnectivityTest, - Endpoint, - LatencyDistribution, - LatencyPercentile, - ProbingDetails, - ReachabilityDetails, -) -from .reachability import ( - CreateConnectivityTestRequest, - DeleteConnectivityTestRequest, - GetConnectivityTestRequest, - ListConnectivityTestsRequest, - ListConnectivityTestsResponse, - OperationMetadata, - RerunConnectivityTestRequest, - UpdateConnectivityTestRequest, -) -from .trace import ( - AbortInfo, - AppEngineVersionInfo, - CloudFunctionInfo, - CloudRunRevisionInfo, - CloudSQLInstanceInfo, - DeliverInfo, - DropInfo, - EndpointInfo, - FirewallInfo, - ForwardInfo, - ForwardingRuleInfo, - GKEMasterInfo, - GoogleServiceInfo, - InstanceInfo, - LoadBalancerBackend, - LoadBalancerBackendInfo, - LoadBalancerInfo, - NatInfo, - NetworkInfo, - ProxyConnectionInfo, - RedisClusterInfo, - RedisInstanceInfo, - RouteInfo, - ServerlessNegInfo, - Step, - StorageBucketInfo, - Trace, - VpcConnectorInfo, - VpnGatewayInfo, - VpnTunnelInfo, - LoadBalancerType, -) - -__all__ = ( - 'ConnectivityTest', - 'Endpoint', - 'LatencyDistribution', - 'LatencyPercentile', - 'ProbingDetails', - 'ReachabilityDetails', - 'CreateConnectivityTestRequest', - 'DeleteConnectivityTestRequest', - 'GetConnectivityTestRequest', - 'ListConnectivityTestsRequest', - 'ListConnectivityTestsResponse', - 'OperationMetadata', - 'RerunConnectivityTestRequest', - 'UpdateConnectivityTestRequest', - 'AbortInfo', - 'AppEngineVersionInfo', - 'CloudFunctionInfo', - 'CloudRunRevisionInfo', - 'CloudSQLInstanceInfo', - 'DeliverInfo', - 'DropInfo', - 'EndpointInfo', - 'FirewallInfo', - 'ForwardInfo', - 'ForwardingRuleInfo', - 'GKEMasterInfo', - 'GoogleServiceInfo', - 'InstanceInfo', - 'LoadBalancerBackend', - 'LoadBalancerBackendInfo', - 'LoadBalancerInfo', - 'NatInfo', - 'NetworkInfo', - 'ProxyConnectionInfo', - 'RedisClusterInfo', - 'RedisInstanceInfo', - 'RouteInfo', - 'ServerlessNegInfo', - 'Step', - 'StorageBucketInfo', - 'Trace', - 'VpcConnectorInfo', - 'VpnGatewayInfo', - 'VpnTunnelInfo', - 'LoadBalancerType', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py deleted file mode 100644 index 5a3ba49e5693..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py +++ /dev/null @@ -1,735 +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.network_management_v1.types import trace -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networkmanagement.v1', - manifest={ - 'ConnectivityTest', - 'Endpoint', - 'ReachabilityDetails', - 'LatencyPercentile', - 'LatencyDistribution', - 'ProbingDetails', - }, -) - - -class ConnectivityTest(proto.Message): - r"""A Connectivity Test for a network reachability analysis. - - Attributes: - name (str): - Identifier. Unique name of the resource using the form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - description (str): - The user-supplied description of the - Connectivity Test. Maximum of 512 characters. - source (google.cloud.network_management_v1.types.Endpoint): - Required. Source specification of the - Connectivity Test. - You can use a combination of source IP address, - virtual machine (VM) instance, or Compute Engine - network to uniquely identify the source - location. - - Examples: - - If the source IP address is an internal IP - address within a Google Cloud Virtual Private - Cloud (VPC) network, then you must also specify - the VPC network. Otherwise, specify the VM - instance, which already contains its internal IP - address and VPC network information. - - If the source of the test is within an - on-premises network, then you must provide the - destination VPC network. - - If the source endpoint is a Compute Engine VM - instance with multiple network interfaces, the - instance itself is not sufficient to identify - the endpoint. So, you must also specify the - source IP address or VPC network. - - A reachability analysis proceeds even if the - source location is ambiguous. However, the test - result may include endpoints that you don't - intend to test. - destination (google.cloud.network_management_v1.types.Endpoint): - Required. Destination specification of the - Connectivity Test. - You can use a combination of destination IP - address, Compute Engine VM instance, or VPC - network to uniquely identify the destination - location. - - Even if the destination IP address is not - unique, the source IP location is unique. - Usually, the analysis can infer the destination - endpoint from route information. - - If the destination you specify is a VM instance - and the instance has multiple network - interfaces, then you must also specify either a - destination IP address or VPC network to - identify the destination interface. - - A reachability analysis proceeds even if the - destination location is ambiguous. However, the - result can include endpoints that you don't - intend to test. - protocol (str): - IP Protocol of the test. When not provided, - "TCP" is assumed. - related_projects (MutableSequence[str]): - Other projects that may be relevant for - reachability analysis. This is applicable to - scenarios where a test can cross project - boundaries. - display_name (str): - Output only. The display name of a - Connectivity Test. - labels (MutableMapping[str, str]): - Resource labels to represent user-provided - metadata. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the test was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the test's - configuration was updated. - reachability_details (google.cloud.network_management_v1.types.ReachabilityDetails): - Output only. The reachability details of this - test from the latest run. The details are - updated when creating a new test, updating an - existing test, or triggering a one-time rerun of - an existing test. - probing_details (google.cloud.network_management_v1.types.ProbingDetails): - Output only. The probing details of this test - from the latest run, present for applicable - tests only. The details are updated when - creating a new test, updating an existing test, - or triggering a one-time rerun of an existing - test. - bypass_firewall_checks (bool): - Whether the test should skip firewall - checking. If not provided, we assume false. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - source: 'Endpoint' = proto.Field( - proto.MESSAGE, - number=3, - message='Endpoint', - ) - destination: 'Endpoint' = proto.Field( - proto.MESSAGE, - number=4, - message='Endpoint', - ) - protocol: str = proto.Field( - proto.STRING, - number=5, - ) - related_projects: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - display_name: str = proto.Field( - proto.STRING, - number=7, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - reachability_details: 'ReachabilityDetails' = proto.Field( - proto.MESSAGE, - number=12, - message='ReachabilityDetails', - ) - probing_details: 'ProbingDetails' = proto.Field( - proto.MESSAGE, - number=14, - message='ProbingDetails', - ) - bypass_firewall_checks: bool = proto.Field( - proto.BOOL, - number=17, - ) - - -class Endpoint(proto.Message): - r"""Source or destination of the Connectivity Test. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - ip_address (str): - The IP address of the endpoint, which can be - an external or internal IP. - port (int): - The IP protocol port of the endpoint. - Only applicable when protocol is TCP or UDP. - instance (str): - A Compute Engine instance URI. - forwarding_rule (str): - A forwarding rule and its corresponding IP - address represent the frontend configuration of - a Google Cloud load balancer. Forwarding rules - are also used for protocol forwarding, Private - Service Connect and other network services to - provide forwarding information in the control - plane. Format: - - projects/{project}/global/forwardingRules/{id} - or - projects/{project}/regions/{region}/forwardingRules/{id} - forwarding_rule_target (google.cloud.network_management_v1.types.Endpoint.ForwardingRuleTarget): - Output only. Specifies the type of the target - of the forwarding rule. - - This field is a member of `oneof`_ ``_forwarding_rule_target``. - load_balancer_id (str): - Output only. ID of the load balancer the - forwarding rule points to. Empty for forwarding - rules not related to load balancers. - - This field is a member of `oneof`_ ``_load_balancer_id``. - load_balancer_type (google.cloud.network_management_v1.types.LoadBalancerType): - Output only. Type of the load balancer the - forwarding rule points to. - - This field is a member of `oneof`_ ``_load_balancer_type``. - gke_master_cluster (str): - A cluster URI for `Google Kubernetes Engine cluster control - plane `__. - fqdn (str): - DNS endpoint of `Google Kubernetes Engine cluster control - plane `__. - Requires gke_master_cluster to be set, can't be used - simultaneoulsly with ip_address or network. Applicable only - to destination endpoint. - cloud_sql_instance (str): - A `Cloud SQL `__ instance URI. - redis_instance (str): - A `Redis - Instance `__ - URI. - redis_cluster (str): - A `Redis - Cluster `__ - URI. - cloud_function (google.cloud.network_management_v1.types.Endpoint.CloudFunctionEndpoint): - A `Cloud Function `__. - app_engine_version (google.cloud.network_management_v1.types.Endpoint.AppEngineVersionEndpoint): - An `App Engine `__ - `service - version `__. - cloud_run_revision (google.cloud.network_management_v1.types.Endpoint.CloudRunRevisionEndpoint): - A `Cloud Run `__ - `revision `__ - network (str): - A Compute Engine network URI. - network_type (google.cloud.network_management_v1.types.Endpoint.NetworkType): - Type of the network where the endpoint is - located. Applicable only to source endpoint, as - destination network type can be inferred from - the source. - project_id (str): - Project ID where the endpoint is located. - The Project ID can be derived from the URI if - you provide a VM instance or network URI. - The following are two cases where you must - provide the project ID: - - 1. Only the IP address is specified, and the IP - address is within a Google Cloud project. - 2. When you are using Shared VPC and the IP - address that you provide is from the service - project. In this case, the network that the - IP address resides in is defined in the host - project. - """ - class NetworkType(proto.Enum): - r"""The type definition of an endpoint's network. Use one of the - following choices: - - Values: - NETWORK_TYPE_UNSPECIFIED (0): - Default type if unspecified. - GCP_NETWORK (1): - A network hosted within Google Cloud. - To receive more detailed output, specify the URI - for the source or destination network. - NON_GCP_NETWORK (2): - A network hosted outside of Google Cloud. - This can be an on-premises network, or a network - hosted by another cloud provider. - """ - NETWORK_TYPE_UNSPECIFIED = 0 - GCP_NETWORK = 1 - NON_GCP_NETWORK = 2 - - class ForwardingRuleTarget(proto.Enum): - r"""Type of the target of a forwarding rule. - - Values: - FORWARDING_RULE_TARGET_UNSPECIFIED (0): - Forwarding rule target is unknown. - INSTANCE (1): - Compute Engine instance for protocol - forwarding. - LOAD_BALANCER (2): - Load Balancer. The specific type can be found from - [load_balancer_type] - [google.cloud.networkmanagement.v1.Endpoint.load_balancer_type]. - VPN_GATEWAY (3): - Classic Cloud VPN Gateway. - PSC (4): - Forwarding Rule is a Private Service Connect - endpoint. - """ - FORWARDING_RULE_TARGET_UNSPECIFIED = 0 - INSTANCE = 1 - LOAD_BALANCER = 2 - VPN_GATEWAY = 3 - PSC = 4 - - class CloudFunctionEndpoint(proto.Message): - r"""Wrapper for Cloud Function attributes. - - Attributes: - uri (str): - A `Cloud Function `__ - name. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - class AppEngineVersionEndpoint(proto.Message): - r"""Wrapper for the App Engine service version attributes. - - Attributes: - uri (str): - An `App Engine `__ - `service - version `__ - name. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - class CloudRunRevisionEndpoint(proto.Message): - r"""Wrapper for Cloud Run revision attributes. - - Attributes: - uri (str): - A `Cloud Run `__ - `revision `__ - URI. The format is: - projects/{project}/locations/{location}/revisions/{revision} - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - ip_address: str = proto.Field( - proto.STRING, - number=1, - ) - port: int = proto.Field( - proto.INT32, - number=2, - ) - instance: str = proto.Field( - proto.STRING, - number=3, - ) - forwarding_rule: str = proto.Field( - proto.STRING, - number=13, - ) - forwarding_rule_target: ForwardingRuleTarget = proto.Field( - proto.ENUM, - number=14, - optional=True, - enum=ForwardingRuleTarget, - ) - load_balancer_id: str = proto.Field( - proto.STRING, - number=15, - optional=True, - ) - load_balancer_type: trace.LoadBalancerType = proto.Field( - proto.ENUM, - number=16, - optional=True, - enum=trace.LoadBalancerType, - ) - gke_master_cluster: str = proto.Field( - proto.STRING, - number=7, - ) - fqdn: str = proto.Field( - proto.STRING, - number=19, - ) - cloud_sql_instance: str = proto.Field( - proto.STRING, - number=8, - ) - redis_instance: str = proto.Field( - proto.STRING, - number=17, - ) - redis_cluster: str = proto.Field( - proto.STRING, - number=18, - ) - cloud_function: CloudFunctionEndpoint = proto.Field( - proto.MESSAGE, - number=10, - message=CloudFunctionEndpoint, - ) - app_engine_version: AppEngineVersionEndpoint = proto.Field( - proto.MESSAGE, - number=11, - message=AppEngineVersionEndpoint, - ) - cloud_run_revision: CloudRunRevisionEndpoint = proto.Field( - proto.MESSAGE, - number=12, - message=CloudRunRevisionEndpoint, - ) - network: str = proto.Field( - proto.STRING, - number=4, - ) - network_type: NetworkType = proto.Field( - proto.ENUM, - number=5, - enum=NetworkType, - ) - project_id: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ReachabilityDetails(proto.Message): - r"""Results of the configuration analysis from the last run of - the test. - - Attributes: - result (google.cloud.network_management_v1.types.ReachabilityDetails.Result): - The overall result of the test's - configuration analysis. - verify_time (google.protobuf.timestamp_pb2.Timestamp): - The time of the configuration analysis. - error (google.rpc.status_pb2.Status): - The details of a failure or a cancellation of - reachability analysis. - traces (MutableSequence[google.cloud.network_management_v1.types.Trace]): - Result may contain a list of traces if a test - has multiple possible paths in the network, such - as when destination endpoint is a load balancer - with multiple backends. - """ - class Result(proto.Enum): - r"""The overall result of the test's configuration analysis. - - Values: - RESULT_UNSPECIFIED (0): - No result was specified. - REACHABLE (1): - Possible scenarios are: - - - The configuration analysis determined that a packet - originating from the source is expected to reach the - destination. - - The analysis didn't complete because the user lacks - permission for some of the resources in the trace. - However, at the time the user's permission became - insufficient, the trace had been successful so far. - UNREACHABLE (2): - A packet originating from the source is - expected to be dropped before reaching the - destination. - AMBIGUOUS (4): - The source and destination endpoints do not - uniquely identify the test location in the - network, and the reachability result contains - multiple traces. For some traces, a packet could - be delivered, and for others, it would not be. - This result is also assigned to configuration - analysis of return path if on its own it should - be REACHABLE, but configuration analysis of - forward path is AMBIGUOUS. - UNDETERMINED (5): - The configuration analysis did not complete. Possible - reasons are: - - - A permissions error occurred--for example, the user might - not have read permission for all of the resources named - in the test. - - An internal error occurred. - - The analyzer received an invalid or unsupported argument - or was unable to identify a known endpoint. - """ - RESULT_UNSPECIFIED = 0 - REACHABLE = 1 - UNREACHABLE = 2 - AMBIGUOUS = 4 - UNDETERMINED = 5 - - result: Result = proto.Field( - proto.ENUM, - number=1, - enum=Result, - ) - verify_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - traces: MutableSequence[trace.Trace] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=trace.Trace, - ) - - -class LatencyPercentile(proto.Message): - r"""Latency percentile rank and value. - - Attributes: - percent (int): - Percentage of samples this data point applies - to. - latency_micros (int): - percent-th percentile of latency observed, in - microseconds. Fraction of percent/100 of samples - have latency lower or equal to the value of this - field. - """ - - percent: int = proto.Field( - proto.INT32, - number=1, - ) - latency_micros: int = proto.Field( - proto.INT64, - number=2, - ) - - -class LatencyDistribution(proto.Message): - r"""Describes measured latency distribution. - - Attributes: - latency_percentiles (MutableSequence[google.cloud.network_management_v1.types.LatencyPercentile]): - Representative latency percentiles. - """ - - latency_percentiles: MutableSequence['LatencyPercentile'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LatencyPercentile', - ) - - -class ProbingDetails(proto.Message): - r"""Results of active probing from the last run of the test. - - Attributes: - result (google.cloud.network_management_v1.types.ProbingDetails.ProbingResult): - The overall result of active probing. - verify_time (google.protobuf.timestamp_pb2.Timestamp): - The time that reachability was assessed - through active probing. - error (google.rpc.status_pb2.Status): - Details about an internal failure or the - cancellation of active probing. - abort_cause (google.cloud.network_management_v1.types.ProbingDetails.ProbingAbortCause): - The reason probing was aborted. - sent_probe_count (int): - Number of probes sent. - successful_probe_count (int): - Number of probes that reached the - destination. - endpoint_info (google.cloud.network_management_v1.types.EndpointInfo): - The source and destination endpoints derived - from the test input and used for active probing. - probing_latency (google.cloud.network_management_v1.types.LatencyDistribution): - Latency as measured by active probing in one - direction: from the source to the destination - endpoint. - destination_egress_location (google.cloud.network_management_v1.types.ProbingDetails.EdgeLocation): - The EdgeLocation from which a packet destined - for/originating from the internet will egress/ingress the - Google network. This will only be populated for a - connectivity test which has an internet destination/source - address. The absence of this field *must not* be used as an - indication that the destination/source is part of the Google - network. - """ - class ProbingResult(proto.Enum): - r"""Overall probing result of the test. - - Values: - PROBING_RESULT_UNSPECIFIED (0): - No result was specified. - REACHABLE (1): - At least 95% of packets reached the - destination. - UNREACHABLE (2): - No packets reached the destination. - REACHABILITY_INCONSISTENT (3): - Less than 95% of packets reached the - destination. - UNDETERMINED (4): - Reachability could not be determined. Possible reasons are: - - - The user lacks permission to access some of the network - resources required to run the test. - - No valid source endpoint could be derived from the - request. - - An internal error occurred. - """ - PROBING_RESULT_UNSPECIFIED = 0 - REACHABLE = 1 - UNREACHABLE = 2 - REACHABILITY_INCONSISTENT = 3 - UNDETERMINED = 4 - - class ProbingAbortCause(proto.Enum): - r"""Abort cause types. - - Values: - PROBING_ABORT_CAUSE_UNSPECIFIED (0): - No reason was specified. - PERMISSION_DENIED (1): - The user lacks permission to access some of - the network resources required to run the test. - NO_SOURCE_LOCATION (2): - No valid source endpoint could be derived - from the request. - """ - PROBING_ABORT_CAUSE_UNSPECIFIED = 0 - PERMISSION_DENIED = 1 - NO_SOURCE_LOCATION = 2 - - class EdgeLocation(proto.Message): - r"""Representation of a network edge location as per - https://cloud.google.com/vpc/docs/edge-locations. - - Attributes: - metropolitan_area (str): - Name of the metropolitan area. - """ - - metropolitan_area: str = proto.Field( - proto.STRING, - number=1, - ) - - result: ProbingResult = proto.Field( - proto.ENUM, - number=1, - enum=ProbingResult, - ) - verify_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - abort_cause: ProbingAbortCause = proto.Field( - proto.ENUM, - number=4, - enum=ProbingAbortCause, - ) - sent_probe_count: int = proto.Field( - proto.INT32, - number=5, - ) - successful_probe_count: int = proto.Field( - proto.INT32, - number=6, - ) - endpoint_info: trace.EndpointInfo = proto.Field( - proto.MESSAGE, - number=7, - message=trace.EndpointInfo, - ) - probing_latency: 'LatencyDistribution' = proto.Field( - proto.MESSAGE, - number=8, - message='LatencyDistribution', - ) - destination_egress_location: EdgeLocation = proto.Field( - proto.MESSAGE, - number=9, - message=EdgeLocation, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py deleted file mode 100644 index ed3cdf469712..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py +++ /dev/null @@ -1,293 +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.network_management_v1.types import connectivity_test -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networkmanagement.v1', - manifest={ - 'ListConnectivityTestsRequest', - 'ListConnectivityTestsResponse', - 'GetConnectivityTestRequest', - 'CreateConnectivityTestRequest', - 'UpdateConnectivityTestRequest', - 'DeleteConnectivityTestRequest', - 'RerunConnectivityTestRequest', - 'OperationMetadata', - }, -) - - -class ListConnectivityTestsRequest(proto.Message): - r"""Request for the ``ListConnectivityTests`` method. - - Attributes: - parent (str): - Required. The parent resource of the Connectivity Tests: - ``projects/{project_id}/locations/global`` - page_size (int): - Number of ``ConnectivityTests`` to return. - page_token (str): - Page token from an earlier query, as returned in - ``next_page_token``. - filter (str): - Lists the ``ConnectivityTests`` that match the filter - expression. A filter expression filters the resources listed - in the response. The expression must be of the form - `` `` where operators: ``<``, - ``>``, ``<=``, ``>=``, ``!=``, ``=``, ``:`` are supported - (colon ``:`` represents a HAS operator which is roughly - synonymous with equality). can refer to a proto or JSON - field, or a synthetic field. Field names can be camelCase or - snake_case. - - Examples: - - - Filter by name: name = - "projects/proj-1/locations/global/connectivityTests/test-1 - - - Filter by labels: - - - Resources that have a key called ``foo`` labels.foo:\* - - Resources that have a key called ``foo`` whose value - is ``bar`` labels.foo = bar - order_by (str): - Field to use to sort the list. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListConnectivityTestsResponse(proto.Message): - r"""Response for the ``ListConnectivityTests`` method. - - Attributes: - resources (MutableSequence[google.cloud.network_management_v1.types.ConnectivityTest]): - List of Connectivity Tests. - next_page_token (str): - Page token to fetch the next set of - Connectivity Tests. - unreachable (MutableSequence[str]): - Locations that could not be reached (when querying all - locations with ``-``). - """ - - @property - def raw_page(self): - return self - - resources: MutableSequence[connectivity_test.ConnectivityTest] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=connectivity_test.ConnectivityTest, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetConnectivityTestRequest(proto.Message): - r"""Request for the ``GetConnectivityTest`` method. - - Attributes: - name (str): - Required. ``ConnectivityTest`` resource name using the form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateConnectivityTestRequest(proto.Message): - r"""Request for the ``CreateConnectivityTest`` method. - - Attributes: - parent (str): - Required. The parent resource of the Connectivity Test to - create: ``projects/{project_id}/locations/global`` - test_id (str): - Required. The logical name of the Connectivity Test in your - project with the following restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-40 characters. - - Must end with a number or a letter. - - Must be unique within the customer project - resource (google.cloud.network_management_v1.types.ConnectivityTest): - Required. A ``ConnectivityTest`` resource - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - test_id: str = proto.Field( - proto.STRING, - number=2, - ) - resource: connectivity_test.ConnectivityTest = proto.Field( - proto.MESSAGE, - number=3, - message=connectivity_test.ConnectivityTest, - ) - - -class UpdateConnectivityTestRequest(proto.Message): - r"""Request for the ``UpdateConnectivityTest`` method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask of fields to update. At least - one path must be supplied in this field. - resource (google.cloud.network_management_v1.types.ConnectivityTest): - Required. Only fields specified in update_mask are updated. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - resource: connectivity_test.ConnectivityTest = proto.Field( - proto.MESSAGE, - number=2, - message=connectivity_test.ConnectivityTest, - ) - - -class DeleteConnectivityTestRequest(proto.Message): - r"""Request for the ``DeleteConnectivityTest`` method. - - Attributes: - name (str): - Required. Connectivity Test resource name using the form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class RerunConnectivityTestRequest(proto.Message): - r"""Request for the ``RerunConnectivityTest`` method. - - Attributes: - name (str): - Required. Connectivity Test resource name using the form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class OperationMetadata(proto.Message): - r"""Metadata describing an [Operation][google.longrunning.Operation] - - 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): - Target of the operation - for example - projects/project-1/locations/global/connectivityTests/test-1 - verb (str): - Name of the verb executed by the operation. - status_detail (str): - Human-readable status of the operation, if - any. - cancel_requested (bool): - Specifies if cancellation was requested for - the operation. - api_version (str): - API version. - """ - - 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_detail: str = proto.Field( - proto.STRING, - number=5, - ) - cancel_requested: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py deleted file mode 100644 index 78741f3894e1..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py +++ /dev/null @@ -1,3164 +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 - - -__protobuf__ = proto.module( - package='google.cloud.networkmanagement.v1', - manifest={ - 'LoadBalancerType', - 'Trace', - 'Step', - 'InstanceInfo', - 'NetworkInfo', - 'FirewallInfo', - 'RouteInfo', - 'GoogleServiceInfo', - 'ForwardingRuleInfo', - 'LoadBalancerInfo', - 'LoadBalancerBackend', - 'VpnGatewayInfo', - 'VpnTunnelInfo', - 'EndpointInfo', - 'DeliverInfo', - 'ForwardInfo', - 'AbortInfo', - 'DropInfo', - 'GKEMasterInfo', - 'CloudSQLInstanceInfo', - 'RedisInstanceInfo', - 'RedisClusterInfo', - 'CloudFunctionInfo', - 'CloudRunRevisionInfo', - 'AppEngineVersionInfo', - 'VpcConnectorInfo', - 'NatInfo', - 'ProxyConnectionInfo', - 'LoadBalancerBackendInfo', - 'StorageBucketInfo', - 'ServerlessNegInfo', - }, -) - - -class LoadBalancerType(proto.Enum): - r"""Type of a load balancer. For more information, see `Summary of - Google Cloud load - balancers `__. - - Values: - LOAD_BALANCER_TYPE_UNSPECIFIED (0): - Forwarding rule points to a different target - than a load balancer or a load balancer type is - unknown. - HTTPS_ADVANCED_LOAD_BALANCER (1): - Global external HTTP(S) load balancer. - HTTPS_LOAD_BALANCER (2): - Global external HTTP(S) load balancer - (classic) - REGIONAL_HTTPS_LOAD_BALANCER (3): - Regional external HTTP(S) load balancer. - INTERNAL_HTTPS_LOAD_BALANCER (4): - Internal HTTP(S) load balancer. - SSL_PROXY_LOAD_BALANCER (5): - External SSL proxy load balancer. - TCP_PROXY_LOAD_BALANCER (6): - External TCP proxy load balancer. - INTERNAL_TCP_PROXY_LOAD_BALANCER (7): - Internal regional TCP proxy load balancer. - NETWORK_LOAD_BALANCER (8): - External TCP/UDP Network load balancer. - LEGACY_NETWORK_LOAD_BALANCER (9): - Target-pool based external TCP/UDP Network - load balancer. - TCP_UDP_INTERNAL_LOAD_BALANCER (10): - Internal TCP/UDP load balancer. - """ - LOAD_BALANCER_TYPE_UNSPECIFIED = 0 - HTTPS_ADVANCED_LOAD_BALANCER = 1 - HTTPS_LOAD_BALANCER = 2 - REGIONAL_HTTPS_LOAD_BALANCER = 3 - INTERNAL_HTTPS_LOAD_BALANCER = 4 - SSL_PROXY_LOAD_BALANCER = 5 - TCP_PROXY_LOAD_BALANCER = 6 - INTERNAL_TCP_PROXY_LOAD_BALANCER = 7 - NETWORK_LOAD_BALANCER = 8 - LEGACY_NETWORK_LOAD_BALANCER = 9 - TCP_UDP_INTERNAL_LOAD_BALANCER = 10 - - -class Trace(proto.Message): - r"""Trace represents one simulated packet forwarding path. - - - Each trace contains multiple ordered steps. - - Each step is in a particular state with associated configuration. - - State is categorized as final or non-final states. - - Each final state has a reason associated. - - Each trace must end with a final state (the last step). - - :: - - |---------------------Trace----------------------| - Step1(State) Step2(State) --- StepN(State(final)) - - Attributes: - endpoint_info (google.cloud.network_management_v1.types.EndpointInfo): - Derived from the source and destination endpoints definition - specified by user request, and validated by the data plane - model. If there are multiple traces starting from different - source locations, then the endpoint_info may be different - between traces. - steps (MutableSequence[google.cloud.network_management_v1.types.Step]): - A trace of a test contains multiple steps - from the initial state to the final state - (delivered, dropped, forwarded, or aborted). - - The steps are ordered by the processing sequence - within the simulated network state machine. It - is critical to preserve the order of the steps - and avoid reordering or sorting them. - forward_trace_id (int): - ID of trace. For forward traces, this ID is - unique for each trace. For return traces, it - matches ID of associated forward trace. A single - forward trace can be associated with none, one - or more than one return trace. - """ - - endpoint_info: 'EndpointInfo' = proto.Field( - proto.MESSAGE, - number=1, - message='EndpointInfo', - ) - steps: MutableSequence['Step'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Step', - ) - forward_trace_id: int = proto.Field( - proto.INT32, - number=4, - ) - - -class Step(proto.Message): - r"""A simulated forwarding path is composed of multiple steps. - Each step has a well-defined state and an associated - configuration. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - description (str): - A description of the step. Usually this is a - summary of the state. - state (google.cloud.network_management_v1.types.Step.State): - Each step is in one of the pre-defined - states. - causes_drop (bool): - This is a step that leads to the final state - Drop. - project_id (str): - Project ID that contains the configuration - this step is validating. - instance (google.cloud.network_management_v1.types.InstanceInfo): - Display information of a Compute Engine - instance. - - This field is a member of `oneof`_ ``step_info``. - firewall (google.cloud.network_management_v1.types.FirewallInfo): - Display information of a Compute Engine - firewall rule. - - This field is a member of `oneof`_ ``step_info``. - route (google.cloud.network_management_v1.types.RouteInfo): - Display information of a Compute Engine - route. - - This field is a member of `oneof`_ ``step_info``. - endpoint (google.cloud.network_management_v1.types.EndpointInfo): - Display information of the source and - destination under analysis. The endpoint - information in an intermediate state may differ - with the initial input, as it might be modified - by state like NAT, or Connection Proxy. - - This field is a member of `oneof`_ ``step_info``. - google_service (google.cloud.network_management_v1.types.GoogleServiceInfo): - Display information of a Google service - - This field is a member of `oneof`_ ``step_info``. - forwarding_rule (google.cloud.network_management_v1.types.ForwardingRuleInfo): - Display information of a Compute Engine - forwarding rule. - - This field is a member of `oneof`_ ``step_info``. - vpn_gateway (google.cloud.network_management_v1.types.VpnGatewayInfo): - Display information of a Compute Engine VPN - gateway. - - This field is a member of `oneof`_ ``step_info``. - vpn_tunnel (google.cloud.network_management_v1.types.VpnTunnelInfo): - Display information of a Compute Engine VPN - tunnel. - - This field is a member of `oneof`_ ``step_info``. - vpc_connector (google.cloud.network_management_v1.types.VpcConnectorInfo): - Display information of a VPC connector. - - This field is a member of `oneof`_ ``step_info``. - deliver (google.cloud.network_management_v1.types.DeliverInfo): - Display information of the final state - "deliver" and reason. - - This field is a member of `oneof`_ ``step_info``. - forward (google.cloud.network_management_v1.types.ForwardInfo): - Display information of the final state - "forward" and reason. - - This field is a member of `oneof`_ ``step_info``. - abort (google.cloud.network_management_v1.types.AbortInfo): - Display information of the final state - "abort" and reason. - - This field is a member of `oneof`_ ``step_info``. - drop (google.cloud.network_management_v1.types.DropInfo): - Display information of the final state "drop" - and reason. - - This field is a member of `oneof`_ ``step_info``. - load_balancer (google.cloud.network_management_v1.types.LoadBalancerInfo): - Display information of the load balancers. Deprecated in - favor of the ``load_balancer_backend_info`` field, not used - in new tests. - - This field is a member of `oneof`_ ``step_info``. - network (google.cloud.network_management_v1.types.NetworkInfo): - Display information of a Google Cloud - network. - - This field is a member of `oneof`_ ``step_info``. - gke_master (google.cloud.network_management_v1.types.GKEMasterInfo): - Display information of a Google Kubernetes - Engine cluster master. - - This field is a member of `oneof`_ ``step_info``. - cloud_sql_instance (google.cloud.network_management_v1.types.CloudSQLInstanceInfo): - Display information of a Cloud SQL instance. - - This field is a member of `oneof`_ ``step_info``. - redis_instance (google.cloud.network_management_v1.types.RedisInstanceInfo): - Display information of a Redis Instance. - - This field is a member of `oneof`_ ``step_info``. - redis_cluster (google.cloud.network_management_v1.types.RedisClusterInfo): - Display information of a Redis Cluster. - - This field is a member of `oneof`_ ``step_info``. - cloud_function (google.cloud.network_management_v1.types.CloudFunctionInfo): - Display information of a Cloud Function. - - This field is a member of `oneof`_ ``step_info``. - app_engine_version (google.cloud.network_management_v1.types.AppEngineVersionInfo): - Display information of an App Engine service - version. - - This field is a member of `oneof`_ ``step_info``. - cloud_run_revision (google.cloud.network_management_v1.types.CloudRunRevisionInfo): - Display information of a Cloud Run revision. - - This field is a member of `oneof`_ ``step_info``. - nat (google.cloud.network_management_v1.types.NatInfo): - Display information of a NAT. - - This field is a member of `oneof`_ ``step_info``. - proxy_connection (google.cloud.network_management_v1.types.ProxyConnectionInfo): - Display information of a ProxyConnection. - - This field is a member of `oneof`_ ``step_info``. - load_balancer_backend_info (google.cloud.network_management_v1.types.LoadBalancerBackendInfo): - Display information of a specific load - balancer backend. - - This field is a member of `oneof`_ ``step_info``. - storage_bucket (google.cloud.network_management_v1.types.StorageBucketInfo): - Display information of a Storage Bucket. Used - only for return traces. - - This field is a member of `oneof`_ ``step_info``. - serverless_neg (google.cloud.network_management_v1.types.ServerlessNegInfo): - Display information of a Serverless network - endpoint group backend. Used only for return - traces. - - This field is a member of `oneof`_ ``step_info``. - """ - class State(proto.Enum): - r"""Type of states that are defined in the network state machine. - Each step in the packet trace is in a specific state. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - START_FROM_INSTANCE (1): - Initial state: packet originating from a - Compute Engine instance. An InstanceInfo is - populated with starting instance information. - START_FROM_INTERNET (2): - Initial state: packet originating from the - internet. The endpoint information is populated. - START_FROM_GOOGLE_SERVICE (27): - Initial state: packet originating from a Google service. The - google_service information is populated. - START_FROM_PRIVATE_NETWORK (3): - Initial state: packet originating from a VPC - or on-premises network with internal source IP. - If the source is a VPC network visible to the - user, a NetworkInfo is populated with details of - the network. - START_FROM_GKE_MASTER (21): - Initial state: packet originating from a - Google Kubernetes Engine cluster master. A - GKEMasterInfo is populated with starting - instance information. - START_FROM_CLOUD_SQL_INSTANCE (22): - Initial state: packet originating from a - Cloud SQL instance. A CloudSQLInstanceInfo is - populated with starting instance information. - START_FROM_REDIS_INSTANCE (32): - Initial state: packet originating from a - Redis instance. A RedisInstanceInfo is populated - with starting instance information. - START_FROM_REDIS_CLUSTER (33): - Initial state: packet originating from a - Redis Cluster. A RedisClusterInfo is populated - with starting Cluster information. - START_FROM_CLOUD_FUNCTION (23): - Initial state: packet originating from a - Cloud Function. A CloudFunctionInfo is populated - with starting function information. - START_FROM_APP_ENGINE_VERSION (25): - Initial state: packet originating from an App - Engine service version. An AppEngineVersionInfo - is populated with starting version information. - START_FROM_CLOUD_RUN_REVISION (26): - Initial state: packet originating from a - Cloud Run revision. A CloudRunRevisionInfo is - populated with starting revision information. - START_FROM_STORAGE_BUCKET (29): - Initial state: packet originating from a Storage Bucket. - Used only for return traces. The storage_bucket information - is populated. - START_FROM_PSC_PUBLISHED_SERVICE (30): - Initial state: packet originating from a - published service that uses Private Service - Connect. Used only for return traces. - START_FROM_SERVERLESS_NEG (31): - Initial state: packet originating from a serverless network - endpoint group backend. Used only for return traces. The - serverless_neg information is populated. - APPLY_INGRESS_FIREWALL_RULE (4): - Config checking state: verify ingress - firewall rule. - APPLY_EGRESS_FIREWALL_RULE (5): - Config checking state: verify egress firewall - rule. - APPLY_ROUTE (6): - Config checking state: verify route. - APPLY_FORWARDING_RULE (7): - Config checking state: match forwarding rule. - ANALYZE_LOAD_BALANCER_BACKEND (28): - Config checking state: verify load balancer - backend configuration. - SPOOFING_APPROVED (8): - Config checking state: packet sent or - received under foreign IP address and allowed. - ARRIVE_AT_INSTANCE (9): - Forwarding state: arriving at a Compute - Engine instance. - ARRIVE_AT_INTERNAL_LOAD_BALANCER (10): - Forwarding state: arriving at a Compute - Engine internal load balancer. - ARRIVE_AT_EXTERNAL_LOAD_BALANCER (11): - Forwarding state: arriving at a Compute - Engine external load balancer. - ARRIVE_AT_VPN_GATEWAY (12): - Forwarding state: arriving at a Cloud VPN - gateway. - ARRIVE_AT_VPN_TUNNEL (13): - Forwarding state: arriving at a Cloud VPN - tunnel. - ARRIVE_AT_VPC_CONNECTOR (24): - Forwarding state: arriving at a VPC - connector. - NAT (14): - Transition state: packet header translated. - PROXY_CONNECTION (15): - Transition state: original connection is - terminated and a new proxied connection is - initiated. - DELIVER (16): - Final state: packet could be delivered. - DROP (17): - Final state: packet could be dropped. - FORWARD (18): - Final state: packet could be forwarded to a - network with an unknown configuration. - ABORT (19): - Final state: analysis is aborted. - VIEWER_PERMISSION_MISSING (20): - Special state: viewer of the test result does - not have permission to see the configuration in - this step. - """ - STATE_UNSPECIFIED = 0 - START_FROM_INSTANCE = 1 - START_FROM_INTERNET = 2 - START_FROM_GOOGLE_SERVICE = 27 - START_FROM_PRIVATE_NETWORK = 3 - START_FROM_GKE_MASTER = 21 - START_FROM_CLOUD_SQL_INSTANCE = 22 - START_FROM_REDIS_INSTANCE = 32 - START_FROM_REDIS_CLUSTER = 33 - START_FROM_CLOUD_FUNCTION = 23 - START_FROM_APP_ENGINE_VERSION = 25 - START_FROM_CLOUD_RUN_REVISION = 26 - START_FROM_STORAGE_BUCKET = 29 - START_FROM_PSC_PUBLISHED_SERVICE = 30 - START_FROM_SERVERLESS_NEG = 31 - APPLY_INGRESS_FIREWALL_RULE = 4 - APPLY_EGRESS_FIREWALL_RULE = 5 - APPLY_ROUTE = 6 - APPLY_FORWARDING_RULE = 7 - ANALYZE_LOAD_BALANCER_BACKEND = 28 - SPOOFING_APPROVED = 8 - ARRIVE_AT_INSTANCE = 9 - ARRIVE_AT_INTERNAL_LOAD_BALANCER = 10 - ARRIVE_AT_EXTERNAL_LOAD_BALANCER = 11 - ARRIVE_AT_VPN_GATEWAY = 12 - ARRIVE_AT_VPN_TUNNEL = 13 - ARRIVE_AT_VPC_CONNECTOR = 24 - NAT = 14 - PROXY_CONNECTION = 15 - DELIVER = 16 - DROP = 17 - FORWARD = 18 - ABORT = 19 - VIEWER_PERMISSION_MISSING = 20 - - description: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - causes_drop: bool = proto.Field( - proto.BOOL, - number=3, - ) - project_id: str = proto.Field( - proto.STRING, - number=4, - ) - instance: 'InstanceInfo' = proto.Field( - proto.MESSAGE, - number=5, - oneof='step_info', - message='InstanceInfo', - ) - firewall: 'FirewallInfo' = proto.Field( - proto.MESSAGE, - number=6, - oneof='step_info', - message='FirewallInfo', - ) - route: 'RouteInfo' = proto.Field( - proto.MESSAGE, - number=7, - oneof='step_info', - message='RouteInfo', - ) - endpoint: 'EndpointInfo' = proto.Field( - proto.MESSAGE, - number=8, - oneof='step_info', - message='EndpointInfo', - ) - google_service: 'GoogleServiceInfo' = proto.Field( - proto.MESSAGE, - number=24, - oneof='step_info', - message='GoogleServiceInfo', - ) - forwarding_rule: 'ForwardingRuleInfo' = proto.Field( - proto.MESSAGE, - number=9, - oneof='step_info', - message='ForwardingRuleInfo', - ) - vpn_gateway: 'VpnGatewayInfo' = proto.Field( - proto.MESSAGE, - number=10, - oneof='step_info', - message='VpnGatewayInfo', - ) - vpn_tunnel: 'VpnTunnelInfo' = proto.Field( - proto.MESSAGE, - number=11, - oneof='step_info', - message='VpnTunnelInfo', - ) - vpc_connector: 'VpcConnectorInfo' = proto.Field( - proto.MESSAGE, - number=21, - oneof='step_info', - message='VpcConnectorInfo', - ) - deliver: 'DeliverInfo' = proto.Field( - proto.MESSAGE, - number=12, - oneof='step_info', - message='DeliverInfo', - ) - forward: 'ForwardInfo' = proto.Field( - proto.MESSAGE, - number=13, - oneof='step_info', - message='ForwardInfo', - ) - abort: 'AbortInfo' = proto.Field( - proto.MESSAGE, - number=14, - oneof='step_info', - message='AbortInfo', - ) - drop: 'DropInfo' = proto.Field( - proto.MESSAGE, - number=15, - oneof='step_info', - message='DropInfo', - ) - load_balancer: 'LoadBalancerInfo' = proto.Field( - proto.MESSAGE, - number=16, - oneof='step_info', - message='LoadBalancerInfo', - ) - network: 'NetworkInfo' = proto.Field( - proto.MESSAGE, - number=17, - oneof='step_info', - message='NetworkInfo', - ) - gke_master: 'GKEMasterInfo' = proto.Field( - proto.MESSAGE, - number=18, - oneof='step_info', - message='GKEMasterInfo', - ) - cloud_sql_instance: 'CloudSQLInstanceInfo' = proto.Field( - proto.MESSAGE, - number=19, - oneof='step_info', - message='CloudSQLInstanceInfo', - ) - redis_instance: 'RedisInstanceInfo' = proto.Field( - proto.MESSAGE, - number=30, - oneof='step_info', - message='RedisInstanceInfo', - ) - redis_cluster: 'RedisClusterInfo' = proto.Field( - proto.MESSAGE, - number=31, - oneof='step_info', - message='RedisClusterInfo', - ) - cloud_function: 'CloudFunctionInfo' = proto.Field( - proto.MESSAGE, - number=20, - oneof='step_info', - message='CloudFunctionInfo', - ) - app_engine_version: 'AppEngineVersionInfo' = proto.Field( - proto.MESSAGE, - number=22, - oneof='step_info', - message='AppEngineVersionInfo', - ) - cloud_run_revision: 'CloudRunRevisionInfo' = proto.Field( - proto.MESSAGE, - number=23, - oneof='step_info', - message='CloudRunRevisionInfo', - ) - nat: 'NatInfo' = proto.Field( - proto.MESSAGE, - number=25, - oneof='step_info', - message='NatInfo', - ) - proxy_connection: 'ProxyConnectionInfo' = proto.Field( - proto.MESSAGE, - number=26, - oneof='step_info', - message='ProxyConnectionInfo', - ) - load_balancer_backend_info: 'LoadBalancerBackendInfo' = proto.Field( - proto.MESSAGE, - number=27, - oneof='step_info', - message='LoadBalancerBackendInfo', - ) - storage_bucket: 'StorageBucketInfo' = proto.Field( - proto.MESSAGE, - number=28, - oneof='step_info', - message='StorageBucketInfo', - ) - serverless_neg: 'ServerlessNegInfo' = proto.Field( - proto.MESSAGE, - number=29, - oneof='step_info', - message='ServerlessNegInfo', - ) - - -class InstanceInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - instance. - - Attributes: - display_name (str): - Name of a Compute Engine instance. - uri (str): - URI of a Compute Engine instance. - interface (str): - Name of the network interface of a Compute - Engine instance. - network_uri (str): - URI of a Compute Engine network. - internal_ip (str): - Internal IP address of the network interface. - external_ip (str): - External IP address of the network interface. - network_tags (MutableSequence[str]): - Network tags configured on the instance. - service_account (str): - Service account authorized for the instance. - psc_network_attachment_uri (str): - URI of the PSC network attachment the NIC is - attached to (if relevant). - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - interface: str = proto.Field( - proto.STRING, - number=3, - ) - network_uri: str = proto.Field( - proto.STRING, - number=4, - ) - internal_ip: str = proto.Field( - proto.STRING, - number=5, - ) - external_ip: str = proto.Field( - proto.STRING, - number=6, - ) - network_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - service_account: str = proto.Field( - proto.STRING, - number=8, - ) - psc_network_attachment_uri: str = proto.Field( - proto.STRING, - number=9, - ) - - -class NetworkInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - network. Next ID: 7 - - Attributes: - display_name (str): - Name of a Compute Engine network. - uri (str): - URI of a Compute Engine network. - matched_subnet_uri (str): - URI of the subnet matching the source IP - address of the test. - matched_ip_range (str): - The IP range of the subnet matching the - source IP address of the test. - region (str): - The region of the subnet matching the source - IP address of the test. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - matched_subnet_uri: str = proto.Field( - proto.STRING, - number=5, - ) - matched_ip_range: str = proto.Field( - proto.STRING, - number=4, - ) - region: str = proto.Field( - proto.STRING, - number=6, - ) - - -class FirewallInfo(proto.Message): - r"""For display only. Metadata associated with a VPC firewall - rule, an implied VPC firewall rule, or a firewall policy rule. - - Attributes: - display_name (str): - The display name of the firewall rule. This - field might be empty for firewall policy rules. - uri (str): - The URI of the firewall rule. This field is - not applicable to implied VPC firewall rules. - direction (str): - Possible values: INGRESS, EGRESS - action (str): - Possible values: ALLOW, DENY, APPLY_SECURITY_PROFILE_GROUP - priority (int): - The priority of the firewall rule. - network_uri (str): - The URI of the VPC network that the firewall - rule is associated with. This field is not - applicable to hierarchical firewall policy - rules. - target_tags (MutableSequence[str]): - The target tags defined by the VPC firewall - rule. This field is not applicable to firewall - policy rules. - target_service_accounts (MutableSequence[str]): - The target service accounts specified by the - firewall rule. - policy (str): - The name of the firewall policy that this - rule is associated with. This field is not - applicable to VPC firewall rules and implied VPC - firewall rules. - policy_uri (str): - The URI of the firewall policy that this rule - is associated with. This field is not applicable - to VPC firewall rules and implied VPC firewall - rules. - firewall_rule_type (google.cloud.network_management_v1.types.FirewallInfo.FirewallRuleType): - The firewall rule's type. - """ - class FirewallRuleType(proto.Enum): - r"""The firewall rule's type. - - Values: - FIREWALL_RULE_TYPE_UNSPECIFIED (0): - Unspecified type. - HIERARCHICAL_FIREWALL_POLICY_RULE (1): - Hierarchical firewall policy rule. For details, see - `Hierarchical firewall policies - overview `__. - VPC_FIREWALL_RULE (2): - VPC firewall rule. For details, see `VPC firewall rules - overview `__. - IMPLIED_VPC_FIREWALL_RULE (3): - Implied VPC firewall rule. For details, see `Implied - rules `__. - SERVERLESS_VPC_ACCESS_MANAGED_FIREWALL_RULE (4): - Implicit firewall rules that are managed by serverless VPC - access to allow ingress access. They are not visible in the - Google Cloud console. For details, see `VPC connector's - implicit - rules `__. - NETWORK_FIREWALL_POLICY_RULE (5): - Global network firewall policy rule. For details, see - `Network firewall - policies `__. - NETWORK_REGIONAL_FIREWALL_POLICY_RULE (6): - Regional network firewall policy rule. For details, see - `Regional network firewall - policies `__. - UNSUPPORTED_FIREWALL_POLICY_RULE (100): - Firewall policy rule containing attributes not yet supported - in Connectivity tests. Firewall analysis is skipped if such - a rule can potentially be matched. Please see the `list of - unsupported - configurations `__. - TRACKING_STATE (101): - Tracking state for response traffic created when request - traffic goes through allow firewall rule. For details, see - `firewall rules - specifications `__ - """ - FIREWALL_RULE_TYPE_UNSPECIFIED = 0 - HIERARCHICAL_FIREWALL_POLICY_RULE = 1 - VPC_FIREWALL_RULE = 2 - IMPLIED_VPC_FIREWALL_RULE = 3 - SERVERLESS_VPC_ACCESS_MANAGED_FIREWALL_RULE = 4 - NETWORK_FIREWALL_POLICY_RULE = 5 - NETWORK_REGIONAL_FIREWALL_POLICY_RULE = 6 - UNSUPPORTED_FIREWALL_POLICY_RULE = 100 - TRACKING_STATE = 101 - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - direction: str = proto.Field( - proto.STRING, - number=3, - ) - action: str = proto.Field( - proto.STRING, - number=4, - ) - priority: int = proto.Field( - proto.INT32, - number=5, - ) - network_uri: str = proto.Field( - proto.STRING, - number=6, - ) - target_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - target_service_accounts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - policy: str = proto.Field( - proto.STRING, - number=9, - ) - policy_uri: str = proto.Field( - proto.STRING, - number=11, - ) - firewall_rule_type: FirewallRuleType = proto.Field( - proto.ENUM, - number=10, - enum=FirewallRuleType, - ) - - -class RouteInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - route. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - route_type (google.cloud.network_management_v1.types.RouteInfo.RouteType): - Type of route. - next_hop_type (google.cloud.network_management_v1.types.RouteInfo.NextHopType): - Type of next hop. - route_scope (google.cloud.network_management_v1.types.RouteInfo.RouteScope): - Indicates where route is applicable. - display_name (str): - Name of a route. - uri (str): - URI of a route (if applicable). - region (str): - Region of the route (if applicable). - dest_ip_range (str): - Destination IP range of the route. - next_hop (str): - Next hop of the route. - network_uri (str): - URI of a Compute Engine network. NETWORK - routes only. - priority (int): - Priority of the route. - instance_tags (MutableSequence[str]): - Instance tags of the route. - src_ip_range (str): - Source IP address range of the route. Policy - based routes only. - dest_port_ranges (MutableSequence[str]): - Destination port ranges of the route. Policy - based routes only. - src_port_ranges (MutableSequence[str]): - Source port ranges of the route. Policy based - routes only. - protocols (MutableSequence[str]): - Protocols of the route. Policy based routes - only. - ncc_hub_uri (str): - URI of a NCC Hub. NCC_HUB routes only. - - This field is a member of `oneof`_ ``_ncc_hub_uri``. - ncc_spoke_uri (str): - URI of a NCC Spoke. NCC_HUB routes only. - - This field is a member of `oneof`_ ``_ncc_spoke_uri``. - advertised_route_source_router_uri (str): - For advertised dynamic routes, the URI of the - Cloud Router that advertised the corresponding - IP prefix. - - This field is a member of `oneof`_ ``_advertised_route_source_router_uri``. - advertised_route_next_hop_uri (str): - For advertised routes, the URI of their next - hop, i.e. the URI of the hybrid endpoint (VPN - tunnel, Interconnect attachment, NCC router - appliance) the advertised prefix is advertised - through, or URI of the source peered network. - - This field is a member of `oneof`_ ``_advertised_route_next_hop_uri``. - """ - class RouteType(proto.Enum): - r"""Type of route: - - Values: - ROUTE_TYPE_UNSPECIFIED (0): - Unspecified type. Default value. - SUBNET (1): - Route is a subnet route automatically created - by the system. - STATIC (2): - Static route created by the user, including - the default route to the internet. - DYNAMIC (3): - Dynamic route exchanged between BGP peers. - PEERING_SUBNET (4): - A subnet route received from peering network. - PEERING_STATIC (5): - A static route received from peering network. - PEERING_DYNAMIC (6): - A dynamic route received from peering - network. - POLICY_BASED (7): - Policy based route. - ADVERTISED (101): - Advertised route. Synthetic route which is - used to transition from the - StartFromPrivateNetwork state in Connectivity - tests. - """ - ROUTE_TYPE_UNSPECIFIED = 0 - SUBNET = 1 - STATIC = 2 - DYNAMIC = 3 - PEERING_SUBNET = 4 - PEERING_STATIC = 5 - PEERING_DYNAMIC = 6 - POLICY_BASED = 7 - ADVERTISED = 101 - - class NextHopType(proto.Enum): - r"""Type of next hop: - - Values: - NEXT_HOP_TYPE_UNSPECIFIED (0): - Unspecified type. Default value. - NEXT_HOP_IP (1): - Next hop is an IP address. - NEXT_HOP_INSTANCE (2): - Next hop is a Compute Engine instance. - NEXT_HOP_NETWORK (3): - Next hop is a VPC network gateway. - NEXT_HOP_PEERING (4): - Next hop is a peering VPC. - NEXT_HOP_INTERCONNECT (5): - Next hop is an interconnect. - NEXT_HOP_VPN_TUNNEL (6): - Next hop is a VPN tunnel. - NEXT_HOP_VPN_GATEWAY (7): - Next hop is a VPN gateway. This scenario only - happens when tracing connectivity from an - on-premises network to Google Cloud through a - VPN. The analysis simulates a packet departing - from the on-premises network through a VPN - tunnel and arriving at a Cloud VPN gateway. - NEXT_HOP_INTERNET_GATEWAY (8): - Next hop is an internet gateway. - NEXT_HOP_BLACKHOLE (9): - Next hop is blackhole; that is, the next hop - either does not exist or is not running. - NEXT_HOP_ILB (10): - Next hop is the forwarding rule of an - Internal Load Balancer. - NEXT_HOP_ROUTER_APPLIANCE (11): - Next hop is a `router appliance - instance `__. - NEXT_HOP_NCC_HUB (12): - Next hop is an NCC hub. - """ - NEXT_HOP_TYPE_UNSPECIFIED = 0 - NEXT_HOP_IP = 1 - NEXT_HOP_INSTANCE = 2 - NEXT_HOP_NETWORK = 3 - NEXT_HOP_PEERING = 4 - NEXT_HOP_INTERCONNECT = 5 - NEXT_HOP_VPN_TUNNEL = 6 - NEXT_HOP_VPN_GATEWAY = 7 - NEXT_HOP_INTERNET_GATEWAY = 8 - NEXT_HOP_BLACKHOLE = 9 - NEXT_HOP_ILB = 10 - NEXT_HOP_ROUTER_APPLIANCE = 11 - NEXT_HOP_NCC_HUB = 12 - - class RouteScope(proto.Enum): - r"""Indicates where routes are applicable. - - Values: - ROUTE_SCOPE_UNSPECIFIED (0): - Unspecified scope. Default value. - NETWORK (1): - Route is applicable to packets in Network. - NCC_HUB (2): - Route is applicable to packets using NCC - Hub's routing table. - """ - ROUTE_SCOPE_UNSPECIFIED = 0 - NETWORK = 1 - NCC_HUB = 2 - - route_type: RouteType = proto.Field( - proto.ENUM, - number=8, - enum=RouteType, - ) - next_hop_type: NextHopType = proto.Field( - proto.ENUM, - number=9, - enum=NextHopType, - ) - route_scope: RouteScope = proto.Field( - proto.ENUM, - number=14, - enum=RouteScope, - ) - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - region: str = proto.Field( - proto.STRING, - number=19, - ) - dest_ip_range: str = proto.Field( - proto.STRING, - number=3, - ) - next_hop: str = proto.Field( - proto.STRING, - number=4, - ) - network_uri: str = proto.Field( - proto.STRING, - number=5, - ) - priority: int = proto.Field( - proto.INT32, - number=6, - ) - instance_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - src_ip_range: str = proto.Field( - proto.STRING, - number=10, - ) - dest_port_ranges: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=11, - ) - src_port_ranges: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=12, - ) - protocols: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=13, - ) - ncc_hub_uri: str = proto.Field( - proto.STRING, - number=15, - optional=True, - ) - ncc_spoke_uri: str = proto.Field( - proto.STRING, - number=16, - optional=True, - ) - advertised_route_source_router_uri: str = proto.Field( - proto.STRING, - number=17, - optional=True, - ) - advertised_route_next_hop_uri: str = proto.Field( - proto.STRING, - number=18, - optional=True, - ) - - -class GoogleServiceInfo(proto.Message): - r"""For display only. Details of a Google Service sending packets to a - VPC network. Although the source IP might be a publicly routable - address, some Google Services use special routes within Google - production infrastructure to reach Compute Engine Instances. - https://cloud.google.com/vpc/docs/routes#special_return_paths - - Attributes: - source_ip (str): - Source IP address. - google_service_type (google.cloud.network_management_v1.types.GoogleServiceInfo.GoogleServiceType): - Recognized type of a Google Service. - """ - class GoogleServiceType(proto.Enum): - r"""Recognized type of a Google Service. - - Values: - GOOGLE_SERVICE_TYPE_UNSPECIFIED (0): - Unspecified Google Service. - IAP (1): - Identity aware proxy. - https://cloud.google.com/iap/docs/using-tcp-forwarding - GFE_PROXY_OR_HEALTH_CHECK_PROBER (2): - One of two services sharing IP ranges: - - - Load Balancer proxy - - Centralized Health Check prober - https://cloud.google.com/load-balancing/docs/firewall-rules - CLOUD_DNS (3): - Connectivity from Cloud DNS to forwarding - targets or alternate name servers that use - private routing. - https://cloud.google.com/dns/docs/zones/forwarding-zones#firewall-rules - https://cloud.google.com/dns/docs/policies#firewall-rules - GOOGLE_API (4): - private.googleapis.com and - restricted.googleapis.com - GOOGLE_API_PSC (5): - Google API via Private Service Connect. - https://cloud.google.com/vpc/docs/configure-private-service-connect-apis - GOOGLE_API_VPC_SC (6): - Google API via VPC Service Controls. - https://cloud.google.com/vpc/docs/configure-private-service-connect-apis - """ - GOOGLE_SERVICE_TYPE_UNSPECIFIED = 0 - IAP = 1 - GFE_PROXY_OR_HEALTH_CHECK_PROBER = 2 - CLOUD_DNS = 3 - GOOGLE_API = 4 - GOOGLE_API_PSC = 5 - GOOGLE_API_VPC_SC = 6 - - source_ip: str = proto.Field( - proto.STRING, - number=1, - ) - google_service_type: GoogleServiceType = proto.Field( - proto.ENUM, - number=2, - enum=GoogleServiceType, - ) - - -class ForwardingRuleInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - forwarding rule. - - Attributes: - display_name (str): - Name of the forwarding rule. - uri (str): - URI of the forwarding rule. - matched_protocol (str): - Protocol defined in the forwarding rule that - matches the packet. - matched_port_range (str): - Port range defined in the forwarding rule - that matches the packet. - vip (str): - VIP of the forwarding rule. - target (str): - Target type of the forwarding rule. - network_uri (str): - Network URI. - region (str): - Region of the forwarding rule. Set only for - regional forwarding rules. - load_balancer_name (str): - Name of the load balancer the forwarding rule - belongs to. Empty for forwarding rules not - related to load balancers (like PSC forwarding - rules). - psc_service_attachment_uri (str): - URI of the PSC service attachment this - forwarding rule targets (if applicable). - psc_google_api_target (str): - PSC Google API target this forwarding rule - targets (if applicable). - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - matched_protocol: str = proto.Field( - proto.STRING, - number=3, - ) - matched_port_range: str = proto.Field( - proto.STRING, - number=6, - ) - vip: str = proto.Field( - proto.STRING, - number=4, - ) - target: str = proto.Field( - proto.STRING, - number=5, - ) - network_uri: str = proto.Field( - proto.STRING, - number=7, - ) - region: str = proto.Field( - proto.STRING, - number=8, - ) - load_balancer_name: str = proto.Field( - proto.STRING, - number=9, - ) - psc_service_attachment_uri: str = proto.Field( - proto.STRING, - number=10, - ) - psc_google_api_target: str = proto.Field( - proto.STRING, - number=11, - ) - - -class LoadBalancerInfo(proto.Message): - r"""For display only. Metadata associated with a load balancer. - - Attributes: - load_balancer_type (google.cloud.network_management_v1.types.LoadBalancerInfo.LoadBalancerType): - Type of the load balancer. - health_check_uri (str): - URI of the health check for the load - balancer. Deprecated and no longer populated as - different load balancer backends might have - different health checks. - backends (MutableSequence[google.cloud.network_management_v1.types.LoadBalancerBackend]): - Information for the loadbalancer backends. - backend_type (google.cloud.network_management_v1.types.LoadBalancerInfo.BackendType): - Type of load balancer's backend - configuration. - backend_uri (str): - Backend configuration URI. - """ - class LoadBalancerType(proto.Enum): - r"""The type definition for a load balancer: - - Values: - LOAD_BALANCER_TYPE_UNSPECIFIED (0): - Type is unspecified. - INTERNAL_TCP_UDP (1): - Internal TCP/UDP load balancer. - NETWORK_TCP_UDP (2): - Network TCP/UDP load balancer. - HTTP_PROXY (3): - HTTP(S) proxy load balancer. - TCP_PROXY (4): - TCP proxy load balancer. - SSL_PROXY (5): - SSL proxy load balancer. - """ - LOAD_BALANCER_TYPE_UNSPECIFIED = 0 - INTERNAL_TCP_UDP = 1 - NETWORK_TCP_UDP = 2 - HTTP_PROXY = 3 - TCP_PROXY = 4 - SSL_PROXY = 5 - - class BackendType(proto.Enum): - r"""The type definition for a load balancer backend - configuration: - - Values: - BACKEND_TYPE_UNSPECIFIED (0): - Type is unspecified. - BACKEND_SERVICE (1): - Backend Service as the load balancer's - backend. - TARGET_POOL (2): - Target Pool as the load balancer's backend. - TARGET_INSTANCE (3): - Target Instance as the load balancer's - backend. - """ - BACKEND_TYPE_UNSPECIFIED = 0 - BACKEND_SERVICE = 1 - TARGET_POOL = 2 - TARGET_INSTANCE = 3 - - load_balancer_type: LoadBalancerType = proto.Field( - proto.ENUM, - number=1, - enum=LoadBalancerType, - ) - health_check_uri: str = proto.Field( - proto.STRING, - number=2, - ) - backends: MutableSequence['LoadBalancerBackend'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LoadBalancerBackend', - ) - backend_type: BackendType = proto.Field( - proto.ENUM, - number=4, - enum=BackendType, - ) - backend_uri: str = proto.Field( - proto.STRING, - number=5, - ) - - -class LoadBalancerBackend(proto.Message): - r"""For display only. Metadata associated with a specific load - balancer backend. - - Attributes: - display_name (str): - Name of a Compute Engine instance or network - endpoint. - uri (str): - URI of a Compute Engine instance or network - endpoint. - health_check_firewall_state (google.cloud.network_management_v1.types.LoadBalancerBackend.HealthCheckFirewallState): - State of the health check firewall - configuration. - health_check_allowing_firewall_rules (MutableSequence[str]): - A list of firewall rule URIs allowing probes - from health check IP ranges. - health_check_blocking_firewall_rules (MutableSequence[str]): - A list of firewall rule URIs blocking probes - from health check IP ranges. - """ - class HealthCheckFirewallState(proto.Enum): - r"""State of a health check firewall configuration: - - Values: - HEALTH_CHECK_FIREWALL_STATE_UNSPECIFIED (0): - State is unspecified. Default state if not - populated. - CONFIGURED (1): - There are configured firewall rules to allow - health check probes to the backend. - MISCONFIGURED (2): - There are firewall rules configured to allow - partial health check ranges or block all health - check ranges. If a health check probe is sent - from denied IP ranges, the health check to the - backend will fail. Then, the backend will be - marked unhealthy and will not receive traffic - sent to the load balancer. - """ - HEALTH_CHECK_FIREWALL_STATE_UNSPECIFIED = 0 - CONFIGURED = 1 - MISCONFIGURED = 2 - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - health_check_firewall_state: HealthCheckFirewallState = proto.Field( - proto.ENUM, - number=3, - enum=HealthCheckFirewallState, - ) - health_check_allowing_firewall_rules: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - health_check_blocking_firewall_rules: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - - -class VpnGatewayInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - VPN gateway. - - Attributes: - display_name (str): - Name of a VPN gateway. - uri (str): - URI of a VPN gateway. - network_uri (str): - URI of a Compute Engine network where the VPN - gateway is configured. - ip_address (str): - IP address of the VPN gateway. - vpn_tunnel_uri (str): - A VPN tunnel that is associated with this VPN - gateway. There may be multiple VPN tunnels - configured on a VPN gateway, and only the one - relevant to the test is displayed. - region (str): - Name of a Google Cloud region where this VPN - gateway is configured. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - network_uri: str = proto.Field( - proto.STRING, - number=3, - ) - ip_address: str = proto.Field( - proto.STRING, - number=4, - ) - vpn_tunnel_uri: str = proto.Field( - proto.STRING, - number=5, - ) - region: str = proto.Field( - proto.STRING, - number=6, - ) - - -class VpnTunnelInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - VPN tunnel. - - Attributes: - display_name (str): - Name of a VPN tunnel. - uri (str): - URI of a VPN tunnel. - source_gateway (str): - URI of the VPN gateway at local end of the - tunnel. - remote_gateway (str): - URI of a VPN gateway at remote end of the - tunnel. - remote_gateway_ip (str): - Remote VPN gateway's IP address. - source_gateway_ip (str): - Local VPN gateway's IP address. - network_uri (str): - URI of a Compute Engine network where the VPN - tunnel is configured. - region (str): - Name of a Google Cloud region where this VPN - tunnel is configured. - routing_type (google.cloud.network_management_v1.types.VpnTunnelInfo.RoutingType): - Type of the routing policy. - """ - class RoutingType(proto.Enum): - r"""Types of VPN routing policy. For details, refer to `Networks and - Tunnel - routing `__. - - Values: - ROUTING_TYPE_UNSPECIFIED (0): - Unspecified type. Default value. - ROUTE_BASED (1): - Route based VPN. - POLICY_BASED (2): - Policy based routing. - DYNAMIC (3): - Dynamic (BGP) routing. - """ - ROUTING_TYPE_UNSPECIFIED = 0 - ROUTE_BASED = 1 - POLICY_BASED = 2 - DYNAMIC = 3 - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - source_gateway: str = proto.Field( - proto.STRING, - number=3, - ) - remote_gateway: str = proto.Field( - proto.STRING, - number=4, - ) - remote_gateway_ip: str = proto.Field( - proto.STRING, - number=5, - ) - source_gateway_ip: str = proto.Field( - proto.STRING, - number=6, - ) - network_uri: str = proto.Field( - proto.STRING, - number=7, - ) - region: str = proto.Field( - proto.STRING, - number=8, - ) - routing_type: RoutingType = proto.Field( - proto.ENUM, - number=9, - enum=RoutingType, - ) - - -class EndpointInfo(proto.Message): - r"""For display only. The specification of the endpoints for the - test. EndpointInfo is derived from source and destination - Endpoint and validated by the backend data plane model. - - Attributes: - source_ip (str): - Source IP address. - destination_ip (str): - Destination IP address. - protocol (str): - IP protocol in string format, for example: - "TCP", "UDP", "ICMP". - source_port (int): - Source port. Only valid when protocol is TCP - or UDP. - destination_port (int): - Destination port. Only valid when protocol is - TCP or UDP. - source_network_uri (str): - URI of the network where this packet - originates from. - destination_network_uri (str): - URI of the network where this packet is sent - to. - source_agent_uri (str): - URI of the source telemetry agent this packet - originates from. - """ - - source_ip: str = proto.Field( - proto.STRING, - number=1, - ) - destination_ip: str = proto.Field( - proto.STRING, - number=2, - ) - protocol: str = proto.Field( - proto.STRING, - number=3, - ) - source_port: int = proto.Field( - proto.INT32, - number=4, - ) - destination_port: int = proto.Field( - proto.INT32, - number=5, - ) - source_network_uri: str = proto.Field( - proto.STRING, - number=6, - ) - destination_network_uri: str = proto.Field( - proto.STRING, - number=7, - ) - source_agent_uri: str = proto.Field( - proto.STRING, - number=8, - ) - - -class DeliverInfo(proto.Message): - r"""Details of the final state "deliver" and associated resource. - - Attributes: - target (google.cloud.network_management_v1.types.DeliverInfo.Target): - Target type where the packet is delivered to. - resource_uri (str): - URI of the resource that the packet is - delivered to. - ip_address (str): - IP address of the target (if applicable). - storage_bucket (str): - Name of the Cloud Storage Bucket the packet - is delivered to (if applicable). - psc_google_api_target (str): - PSC Google API target the packet is delivered - to (if applicable). - """ - class Target(proto.Enum): - r"""Deliver target types: - - Values: - TARGET_UNSPECIFIED (0): - Target not specified. - INSTANCE (1): - Target is a Compute Engine instance. - INTERNET (2): - Target is the internet. - GOOGLE_API (3): - Target is a Google API. - GKE_MASTER (4): - Target is a Google Kubernetes Engine cluster - master. - CLOUD_SQL_INSTANCE (5): - Target is a Cloud SQL instance. - PSC_PUBLISHED_SERVICE (6): - Target is a published service that uses `Private Service - Connect `__. - PSC_GOOGLE_API (7): - Target is Google APIs that use `Private Service - Connect `__. - PSC_VPC_SC (8): - Target is a VPC-SC that uses `Private Service - Connect `__. - SERVERLESS_NEG (9): - Target is a serverless network endpoint - group. - STORAGE_BUCKET (10): - Target is a Cloud Storage bucket. - PRIVATE_NETWORK (11): - Target is a private network. Used only for - return traces. - CLOUD_FUNCTION (12): - Target is a Cloud Function. Used only for - return traces. - APP_ENGINE_VERSION (13): - Target is a App Engine service version. Used - only for return traces. - CLOUD_RUN_REVISION (14): - Target is a Cloud Run revision. Used only for - return traces. - GOOGLE_MANAGED_SERVICE (15): - Target is a Google-managed service. Used only - for return traces. - REDIS_INSTANCE (16): - Target is a Redis Instance. - REDIS_CLUSTER (17): - Target is a Redis Cluster. - """ - TARGET_UNSPECIFIED = 0 - INSTANCE = 1 - INTERNET = 2 - GOOGLE_API = 3 - GKE_MASTER = 4 - CLOUD_SQL_INSTANCE = 5 - PSC_PUBLISHED_SERVICE = 6 - PSC_GOOGLE_API = 7 - PSC_VPC_SC = 8 - SERVERLESS_NEG = 9 - STORAGE_BUCKET = 10 - PRIVATE_NETWORK = 11 - CLOUD_FUNCTION = 12 - APP_ENGINE_VERSION = 13 - CLOUD_RUN_REVISION = 14 - GOOGLE_MANAGED_SERVICE = 15 - REDIS_INSTANCE = 16 - REDIS_CLUSTER = 17 - - target: Target = proto.Field( - proto.ENUM, - number=1, - enum=Target, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=2, - ) - ip_address: str = proto.Field( - proto.STRING, - number=3, - ) - storage_bucket: str = proto.Field( - proto.STRING, - number=4, - ) - psc_google_api_target: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ForwardInfo(proto.Message): - r"""Details of the final state "forward" and associated resource. - - Attributes: - target (google.cloud.network_management_v1.types.ForwardInfo.Target): - Target type where this packet is forwarded - to. - resource_uri (str): - URI of the resource that the packet is - forwarded to. - ip_address (str): - IP address of the target (if applicable). - """ - class Target(proto.Enum): - r"""Forward target types. - - Values: - TARGET_UNSPECIFIED (0): - Target not specified. - PEERING_VPC (1): - Forwarded to a VPC peering network. - VPN_GATEWAY (2): - Forwarded to a Cloud VPN gateway. - INTERCONNECT (3): - Forwarded to a Cloud Interconnect connection. - GKE_MASTER (4): - Forwarded to a Google Kubernetes Engine - Container cluster master. - IMPORTED_CUSTOM_ROUTE_NEXT_HOP (5): - Forwarded to the next hop of a custom route - imported from a peering VPC. - CLOUD_SQL_INSTANCE (6): - Forwarded to a Cloud SQL instance. - ANOTHER_PROJECT (7): - Forwarded to a VPC network in another - project. - NCC_HUB (8): - Forwarded to an NCC Hub. - ROUTER_APPLIANCE (9): - Forwarded to a router appliance. - """ - TARGET_UNSPECIFIED = 0 - PEERING_VPC = 1 - VPN_GATEWAY = 2 - INTERCONNECT = 3 - GKE_MASTER = 4 - IMPORTED_CUSTOM_ROUTE_NEXT_HOP = 5 - CLOUD_SQL_INSTANCE = 6 - ANOTHER_PROJECT = 7 - NCC_HUB = 8 - ROUTER_APPLIANCE = 9 - - target: Target = proto.Field( - proto.ENUM, - number=1, - enum=Target, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=2, - ) - ip_address: str = proto.Field( - proto.STRING, - number=3, - ) - - -class AbortInfo(proto.Message): - r"""Details of the final state "abort" and associated resource. - - Attributes: - cause (google.cloud.network_management_v1.types.AbortInfo.Cause): - Causes that the analysis is aborted. - resource_uri (str): - URI of the resource that caused the abort. - ip_address (str): - IP address that caused the abort. - projects_missing_permission (MutableSequence[str]): - List of project IDs the user specified in the request but - lacks access to. In this case, analysis is aborted with the - PERMISSION_DENIED cause. - """ - class Cause(proto.Enum): - r"""Abort cause types: - - Values: - CAUSE_UNSPECIFIED (0): - Cause is unspecified. - UNKNOWN_NETWORK (1): - Aborted due to unknown network. Deprecated, - not used in the new tests. - UNKNOWN_PROJECT (3): - Aborted because no project information can be - derived from the test input. Deprecated, not - used in the new tests. - NO_EXTERNAL_IP (7): - Aborted because traffic is sent from a public - IP to an instance without an external IP. - Deprecated, not used in the new tests. - UNINTENDED_DESTINATION (8): - Aborted because none of the traces matches - destination information specified in the input - test request. Deprecated, not used in the new - tests. - SOURCE_ENDPOINT_NOT_FOUND (11): - Aborted because the source endpoint could not - be found. Deprecated, not used in the new tests. - MISMATCHED_SOURCE_NETWORK (12): - Aborted because the source network does not - match the source endpoint. Deprecated, not used - in the new tests. - DESTINATION_ENDPOINT_NOT_FOUND (13): - Aborted because the destination endpoint - could not be found. Deprecated, not used in the - new tests. - MISMATCHED_DESTINATION_NETWORK (14): - Aborted because the destination network does - not match the destination endpoint. Deprecated, - not used in the new tests. - UNKNOWN_IP (2): - Aborted because no endpoint with the packet's - destination IP address is found. - GOOGLE_MANAGED_SERVICE_UNKNOWN_IP (32): - Aborted because no endpoint with the packet's - destination IP is found in the Google-managed - project. - SOURCE_IP_ADDRESS_NOT_IN_SOURCE_NETWORK (23): - Aborted because the source IP address doesn't - belong to any of the subnets of the source VPC - network. - PERMISSION_DENIED (4): - Aborted because user lacks permission to - access all or part of the network configurations - required to run the test. - PERMISSION_DENIED_NO_CLOUD_NAT_CONFIGS (28): - Aborted because user lacks permission to - access Cloud NAT configs required to run the - test. - PERMISSION_DENIED_NO_NEG_ENDPOINT_CONFIGS (29): - Aborted because user lacks permission to - access Network endpoint group endpoint configs - required to run the test. - PERMISSION_DENIED_NO_CLOUD_ROUTER_CONFIGS (36): - Aborted because user lacks permission to - access Cloud Router configs required to run the - test. - NO_SOURCE_LOCATION (5): - Aborted because no valid source or - destination endpoint is derived from the input - test request. - INVALID_ARGUMENT (6): - Aborted because the source or destination - endpoint specified in the request is invalid. - Some examples: - - - The request might contain malformed resource - URI, project ID, or IP address. - - The request might contain inconsistent - information (for example, the request might - include both the instance and the network, but - the instance might not have a NIC in that - network). - TRACE_TOO_LONG (9): - Aborted because the number of steps in the - trace exceeds a certain limit. It might be - caused by a routing loop. - INTERNAL_ERROR (10): - Aborted due to internal server error. - UNSUPPORTED (15): - Aborted because the test scenario is not - supported. - MISMATCHED_IP_VERSION (16): - Aborted because the source and destination - resources have no common IP version. - GKE_KONNECTIVITY_PROXY_UNSUPPORTED (17): - Aborted because the connection between the - control plane and the node of the source cluster - is initiated by the node and managed by the - Konnectivity proxy. - RESOURCE_CONFIG_NOT_FOUND (18): - Aborted because expected resource - configuration was missing. - VM_INSTANCE_CONFIG_NOT_FOUND (24): - Aborted because expected VM instance - configuration was missing. - NETWORK_CONFIG_NOT_FOUND (25): - Aborted because expected network - configuration was missing. - FIREWALL_CONFIG_NOT_FOUND (26): - Aborted because expected firewall - configuration was missing. - ROUTE_CONFIG_NOT_FOUND (27): - Aborted because expected route configuration - was missing. - GOOGLE_MANAGED_SERVICE_AMBIGUOUS_PSC_ENDPOINT (19): - Aborted because a PSC endpoint selection for - the Google-managed service is ambiguous (several - PSC endpoints satisfy test input). - SOURCE_PSC_CLOUD_SQL_UNSUPPORTED (20): - Aborted because tests with a PSC-based Cloud - SQL instance as a source are not supported. - SOURCE_REDIS_CLUSTER_UNSUPPORTED (34): - Aborted because tests with a Redis Cluster as - a source are not supported. - SOURCE_REDIS_INSTANCE_UNSUPPORTED (35): - Aborted because tests with a Redis Instance - as a source are not supported. - SOURCE_FORWARDING_RULE_UNSUPPORTED (21): - Aborted because tests with a forwarding rule - as a source are not supported. - NON_ROUTABLE_IP_ADDRESS (22): - Aborted because one of the endpoints is a - non-routable IP address (loopback, link-local, - etc). - UNKNOWN_ISSUE_IN_GOOGLE_MANAGED_PROJECT (30): - Aborted due to an unknown issue in the - Google-managed project. - UNSUPPORTED_GOOGLE_MANAGED_PROJECT_CONFIG (31): - Aborted due to an unsupported configuration - of the Google-managed project. - """ - CAUSE_UNSPECIFIED = 0 - UNKNOWN_NETWORK = 1 - UNKNOWN_PROJECT = 3 - NO_EXTERNAL_IP = 7 - UNINTENDED_DESTINATION = 8 - SOURCE_ENDPOINT_NOT_FOUND = 11 - MISMATCHED_SOURCE_NETWORK = 12 - DESTINATION_ENDPOINT_NOT_FOUND = 13 - MISMATCHED_DESTINATION_NETWORK = 14 - UNKNOWN_IP = 2 - GOOGLE_MANAGED_SERVICE_UNKNOWN_IP = 32 - SOURCE_IP_ADDRESS_NOT_IN_SOURCE_NETWORK = 23 - PERMISSION_DENIED = 4 - PERMISSION_DENIED_NO_CLOUD_NAT_CONFIGS = 28 - PERMISSION_DENIED_NO_NEG_ENDPOINT_CONFIGS = 29 - PERMISSION_DENIED_NO_CLOUD_ROUTER_CONFIGS = 36 - NO_SOURCE_LOCATION = 5 - INVALID_ARGUMENT = 6 - TRACE_TOO_LONG = 9 - INTERNAL_ERROR = 10 - UNSUPPORTED = 15 - MISMATCHED_IP_VERSION = 16 - GKE_KONNECTIVITY_PROXY_UNSUPPORTED = 17 - RESOURCE_CONFIG_NOT_FOUND = 18 - VM_INSTANCE_CONFIG_NOT_FOUND = 24 - NETWORK_CONFIG_NOT_FOUND = 25 - FIREWALL_CONFIG_NOT_FOUND = 26 - ROUTE_CONFIG_NOT_FOUND = 27 - GOOGLE_MANAGED_SERVICE_AMBIGUOUS_PSC_ENDPOINT = 19 - SOURCE_PSC_CLOUD_SQL_UNSUPPORTED = 20 - SOURCE_REDIS_CLUSTER_UNSUPPORTED = 34 - SOURCE_REDIS_INSTANCE_UNSUPPORTED = 35 - SOURCE_FORWARDING_RULE_UNSUPPORTED = 21 - NON_ROUTABLE_IP_ADDRESS = 22 - UNKNOWN_ISSUE_IN_GOOGLE_MANAGED_PROJECT = 30 - UNSUPPORTED_GOOGLE_MANAGED_PROJECT_CONFIG = 31 - - cause: Cause = proto.Field( - proto.ENUM, - number=1, - enum=Cause, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=2, - ) - ip_address: str = proto.Field( - proto.STRING, - number=4, - ) - projects_missing_permission: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class DropInfo(proto.Message): - r"""Details of the final state "drop" and associated resource. - - Attributes: - cause (google.cloud.network_management_v1.types.DropInfo.Cause): - Cause that the packet is dropped. - resource_uri (str): - URI of the resource that caused the drop. - source_ip (str): - Source IP address of the dropped packet (if - relevant). - destination_ip (str): - Destination IP address of the dropped packet - (if relevant). - region (str): - Region of the dropped packet (if relevant). - """ - class Cause(proto.Enum): - r"""Drop cause types: - - Values: - CAUSE_UNSPECIFIED (0): - Cause is unspecified. - UNKNOWN_EXTERNAL_ADDRESS (1): - Destination external address cannot be - resolved to a known target. If the address is - used in a Google Cloud project, provide the - project ID as test input. - FOREIGN_IP_DISALLOWED (2): - A Compute Engine instance can only send or receive a packet - with a foreign IP address if ip_forward is enabled. - FIREWALL_RULE (3): - Dropped due to a firewall rule, unless - allowed due to connection tracking. - NO_ROUTE (4): - Dropped due to no matching routes. - ROUTE_BLACKHOLE (5): - Dropped due to invalid route. Route's next - hop is a blackhole. - ROUTE_WRONG_NETWORK (6): - Packet is sent to a wrong (unintended) - network. Example: you trace a packet from - VM1:Network1 to VM2:Network2, however, the route - configured in Network1 sends the packet destined - for VM2's IP address to Network3. - ROUTE_NEXT_HOP_IP_ADDRESS_NOT_RESOLVED (42): - Route's next hop IP address cannot be - resolved to a GCP resource. - ROUTE_NEXT_HOP_RESOURCE_NOT_FOUND (43): - Route's next hop resource is not found. - ROUTE_NEXT_HOP_INSTANCE_WRONG_NETWORK (49): - Route's next hop instance doesn't have a NIC - in the route's network. - ROUTE_NEXT_HOP_INSTANCE_NON_PRIMARY_IP (50): - Route's next hop IP address is not a primary - IP address of the next hop instance. - ROUTE_NEXT_HOP_FORWARDING_RULE_IP_MISMATCH (51): - Route's next hop forwarding rule doesn't - match next hop IP address. - ROUTE_NEXT_HOP_VPN_TUNNEL_NOT_ESTABLISHED (52): - Route's next hop VPN tunnel is down (does not - have valid IKE SAs). - ROUTE_NEXT_HOP_FORWARDING_RULE_TYPE_INVALID (53): - Route's next hop forwarding rule type is - invalid (it's not a forwarding rule of the - internal passthrough load balancer). - NO_ROUTE_FROM_INTERNET_TO_PRIVATE_IPV6_ADDRESS (44): - Packet is sent from the Internet to the - private IPv6 address. - VPN_TUNNEL_LOCAL_SELECTOR_MISMATCH (45): - The packet does not match a policy-based VPN - tunnel local selector. - VPN_TUNNEL_REMOTE_SELECTOR_MISMATCH (46): - The packet does not match a policy-based VPN - tunnel remote selector. - PRIVATE_TRAFFIC_TO_INTERNET (7): - Packet with internal destination address sent - to the internet gateway. - PRIVATE_GOOGLE_ACCESS_DISALLOWED (8): - Instance with only an internal IP address - tries to access Google API and services, but - private Google access is not enabled in the - subnet. - PRIVATE_GOOGLE_ACCESS_VIA_VPN_TUNNEL_UNSUPPORTED (47): - Source endpoint tries to access Google API - and services through the VPN tunnel to another - network, but Private Google Access needs to be - enabled in the source endpoint network. - NO_EXTERNAL_ADDRESS (9): - Instance with only an internal IP address - tries to access external hosts, but Cloud NAT is - not enabled in the subnet, unless special - configurations on a VM allow this connection. - UNKNOWN_INTERNAL_ADDRESS (10): - Destination internal address cannot be - resolved to a known target. If this is a shared - VPC scenario, verify if the service project ID - is provided as test input. Otherwise, verify if - the IP address is being used in the project. - FORWARDING_RULE_MISMATCH (11): - Forwarding rule's protocol and ports do not - match the packet header. - FORWARDING_RULE_NO_INSTANCES (12): - Forwarding rule does not have backends - configured. - FIREWALL_BLOCKING_LOAD_BALANCER_BACKEND_HEALTH_CHECK (13): - Firewalls block the health check probes to the backends and - cause the backends to be unavailable for traffic from the - load balancer. For more details, see `Health check firewall - rules `__. - INSTANCE_NOT_RUNNING (14): - Packet is sent from or to a Compute Engine - instance that is not in a running state. - GKE_CLUSTER_NOT_RUNNING (27): - Packet sent from or to a GKE cluster that is - not in running state. - CLOUD_SQL_INSTANCE_NOT_RUNNING (28): - Packet sent from or to a Cloud SQL instance - that is not in running state. - REDIS_INSTANCE_NOT_RUNNING (68): - Packet sent from or to a Redis Instance that - is not in running state. - REDIS_CLUSTER_NOT_RUNNING (69): - Packet sent from or to a Redis Cluster that - is not in running state. - TRAFFIC_TYPE_BLOCKED (15): - The type of traffic is blocked and the user cannot configure - a firewall rule to enable it. See `Always blocked - traffic `__ - for more details. - GKE_MASTER_UNAUTHORIZED_ACCESS (16): - Access to Google Kubernetes Engine cluster master's endpoint - is not authorized. See `Access to the cluster - endpoints `__ - for more details. - CLOUD_SQL_INSTANCE_UNAUTHORIZED_ACCESS (17): - Access to the Cloud SQL instance endpoint is not authorized. - See `Authorizing with authorized - networks `__ - for more details. - DROPPED_INSIDE_GKE_SERVICE (18): - Packet was dropped inside Google Kubernetes - Engine Service. - DROPPED_INSIDE_CLOUD_SQL_SERVICE (19): - Packet was dropped inside Cloud SQL Service. - GOOGLE_MANAGED_SERVICE_NO_PEERING (20): - Packet was dropped because there is no - peering between the originating network and the - Google Managed Services Network. - GOOGLE_MANAGED_SERVICE_NO_PSC_ENDPOINT (38): - Packet was dropped because the Google-managed - service uses Private Service Connect (PSC), but - the PSC endpoint is not found in the project. - GKE_PSC_ENDPOINT_MISSING (36): - Packet was dropped because the GKE cluster - uses Private Service Connect (PSC), but the PSC - endpoint is not found in the project. - CLOUD_SQL_INSTANCE_NO_IP_ADDRESS (21): - Packet was dropped because the Cloud SQL - instance has neither a private nor a public IP - address. - GKE_CONTROL_PLANE_REGION_MISMATCH (30): - Packet was dropped because a GKE cluster - private endpoint is unreachable from a region - different from the cluster's region. - PUBLIC_GKE_CONTROL_PLANE_TO_PRIVATE_DESTINATION (31): - Packet sent from a public GKE cluster control - plane to a private IP address. - GKE_CONTROL_PLANE_NO_ROUTE (32): - Packet was dropped because there is no route - from a GKE cluster control plane to a - destination network. - CLOUD_SQL_INSTANCE_NOT_CONFIGURED_FOR_EXTERNAL_TRAFFIC (33): - Packet sent from a Cloud SQL instance to an - external IP address is not allowed. The Cloud - SQL instance is not configured to send packets - to external IP addresses. - PUBLIC_CLOUD_SQL_INSTANCE_TO_PRIVATE_DESTINATION (34): - Packet sent from a Cloud SQL instance with - only a public IP address to a private IP - address. - CLOUD_SQL_INSTANCE_NO_ROUTE (35): - Packet was dropped because there is no route - from a Cloud SQL instance to a destination - network. - CLOUD_SQL_CONNECTOR_REQUIRED (63): - Packet was dropped because the Cloud SQL - instance requires all connections to use Cloud - SQL connectors and to target the Cloud SQL proxy - port (3307). - CLOUD_FUNCTION_NOT_ACTIVE (22): - Packet could be dropped because the Cloud - Function is not in an active status. - VPC_CONNECTOR_NOT_SET (23): - Packet could be dropped because no VPC - connector is set. - VPC_CONNECTOR_NOT_RUNNING (24): - Packet could be dropped because the VPC - connector is not in a running state. - VPC_CONNECTOR_SERVERLESS_TRAFFIC_BLOCKED (60): - Packet could be dropped because the traffic - from the serverless service to the VPC connector - is not allowed. - VPC_CONNECTOR_HEALTH_CHECK_TRAFFIC_BLOCKED (61): - Packet could be dropped because the health - check traffic to the VPC connector is not - allowed. - FORWARDING_RULE_REGION_MISMATCH (25): - Packet could be dropped because it was sent - from a different region to a regional forwarding - without global access. - PSC_CONNECTION_NOT_ACCEPTED (26): - The Private Service Connect endpoint is in a - project that is not approved to connect to the - service. - PSC_ENDPOINT_ACCESSED_FROM_PEERED_NETWORK (41): - The packet is sent to the Private Service Connect endpoint - over the peering, but `it's not - supported `__. - PSC_NEG_PRODUCER_ENDPOINT_NO_GLOBAL_ACCESS (48): - The packet is sent to the Private Service - Connect backend (network endpoint group), but - the producer PSC forwarding rule does not have - global access enabled. - PSC_NEG_PRODUCER_FORWARDING_RULE_MULTIPLE_PORTS (54): - The packet is sent to the Private Service - Connect backend (network endpoint group), but - the producer PSC forwarding rule has multiple - ports specified. - CLOUD_SQL_PSC_NEG_UNSUPPORTED (58): - The packet is sent to the Private Service - Connect backend (network endpoint group) - targeting a Cloud SQL service attachment, but - this configuration is not supported. - NO_NAT_SUBNETS_FOR_PSC_SERVICE_ATTACHMENT (57): - No NAT subnets are defined for the PSC - service attachment. - PSC_TRANSITIVITY_NOT_PROPAGATED (64): - PSC endpoint is accessed via NCC, but PSC - transitivity configuration is not yet - propagated. - HYBRID_NEG_NON_DYNAMIC_ROUTE_MATCHED (55): - The packet sent from the hybrid NEG proxy - matches a non-dynamic route, but such a - configuration is not supported. - HYBRID_NEG_NON_LOCAL_DYNAMIC_ROUTE_MATCHED (56): - The packet sent from the hybrid NEG proxy - matches a dynamic route with a next hop in a - different region, but such a configuration is - not supported. - CLOUD_RUN_REVISION_NOT_READY (29): - Packet sent from a Cloud Run revision that is - not ready. - DROPPED_INSIDE_PSC_SERVICE_PRODUCER (37): - Packet was dropped inside Private Service - Connect service producer. - LOAD_BALANCER_HAS_NO_PROXY_SUBNET (39): - Packet sent to a load balancer, which - requires a proxy-only subnet and the subnet is - not found. - CLOUD_NAT_NO_ADDRESSES (40): - Packet sent to Cloud Nat without active NAT - IPs. - ROUTING_LOOP (59): - Packet is stuck in a routing loop. - DROPPED_INSIDE_GOOGLE_MANAGED_SERVICE (62): - Packet is dropped inside a Google-managed - service due to being delivered in return trace - to an endpoint that doesn't match the endpoint - the packet was sent from in forward trace. Used - only for return traces. - LOAD_BALANCER_BACKEND_INVALID_NETWORK (65): - Packet is dropped due to a load balancer - backend instance not having a network interface - in the network expected by the load balancer. - BACKEND_SERVICE_NAMED_PORT_NOT_DEFINED (66): - Packet is dropped due to a backend service - named port not being defined on the instance - group level. - DESTINATION_IS_PRIVATE_NAT_IP_RANGE (67): - Packet is dropped due to a destination IP - range being part of a Private NAT IP range. - DROPPED_INSIDE_REDIS_INSTANCE_SERVICE (70): - Generic drop cause for a packet being dropped - inside a Redis Instance service project. - REDIS_INSTANCE_UNSUPPORTED_PORT (71): - Packet is dropped due to an unsupported port - being used to connect to a Redis Instance. Port - 6379 should be used to connect to a Redis - Instance. - REDIS_INSTANCE_CONNECTING_FROM_PUPI_ADDRESS (72): - Packet is dropped due to connecting from PUPI - address to a PSA based Redis Instance. - REDIS_INSTANCE_NO_ROUTE_TO_DESTINATION_NETWORK (73): - Packet is dropped due to no route to the - destination network. - REDIS_INSTANCE_NO_EXTERNAL_IP (74): - Redis Instance does not have an external IP - address. - REDIS_INSTANCE_UNSUPPORTED_PROTOCOL (78): - Packet is dropped due to an unsupported - protocol being used to connect to a Redis - Instance. Only TCP connections are accepted by a - Redis Instance. - DROPPED_INSIDE_REDIS_CLUSTER_SERVICE (75): - Generic drop cause for a packet being dropped - inside a Redis Cluster service project. - REDIS_CLUSTER_UNSUPPORTED_PORT (76): - Packet is dropped due to an unsupported port - being used to connect to a Redis Cluster. Ports - 6379 and 11000 to 13047 should be used to - connect to a Redis Cluster. - REDIS_CLUSTER_NO_EXTERNAL_IP (77): - Redis Cluster does not have an external IP - address. - REDIS_CLUSTER_UNSUPPORTED_PROTOCOL (79): - Packet is dropped due to an unsupported - protocol being used to connect to a Redis - Cluster. Only TCP connections are accepted by a - Redis Cluster. - NO_ADVERTISED_ROUTE_TO_GCP_DESTINATION (80): - Packet from the non-GCP (on-prem) or unknown - GCP network is dropped due to the destination IP - address not belonging to any IP prefix - advertised via BGP by the Cloud Router. - NO_TRAFFIC_SELECTOR_TO_GCP_DESTINATION (81): - Packet from the non-GCP (on-prem) or unknown - GCP network is dropped due to the destination IP - address not belonging to any IP prefix included - to the local traffic selector of the VPN tunnel. - NO_KNOWN_ROUTE_FROM_PEERED_NETWORK_TO_DESTINATION (82): - Packet from the unknown peered network is - dropped due to no known route from the source - network to the destination IP address. - PRIVATE_NAT_TO_PSC_ENDPOINT_UNSUPPORTED (83): - Sending packets processed by the Private NAT - Gateways to the Private Service Connect - endpoints is not supported. - """ - CAUSE_UNSPECIFIED = 0 - UNKNOWN_EXTERNAL_ADDRESS = 1 - FOREIGN_IP_DISALLOWED = 2 - FIREWALL_RULE = 3 - NO_ROUTE = 4 - ROUTE_BLACKHOLE = 5 - ROUTE_WRONG_NETWORK = 6 - ROUTE_NEXT_HOP_IP_ADDRESS_NOT_RESOLVED = 42 - ROUTE_NEXT_HOP_RESOURCE_NOT_FOUND = 43 - ROUTE_NEXT_HOP_INSTANCE_WRONG_NETWORK = 49 - ROUTE_NEXT_HOP_INSTANCE_NON_PRIMARY_IP = 50 - ROUTE_NEXT_HOP_FORWARDING_RULE_IP_MISMATCH = 51 - ROUTE_NEXT_HOP_VPN_TUNNEL_NOT_ESTABLISHED = 52 - ROUTE_NEXT_HOP_FORWARDING_RULE_TYPE_INVALID = 53 - NO_ROUTE_FROM_INTERNET_TO_PRIVATE_IPV6_ADDRESS = 44 - VPN_TUNNEL_LOCAL_SELECTOR_MISMATCH = 45 - VPN_TUNNEL_REMOTE_SELECTOR_MISMATCH = 46 - PRIVATE_TRAFFIC_TO_INTERNET = 7 - PRIVATE_GOOGLE_ACCESS_DISALLOWED = 8 - PRIVATE_GOOGLE_ACCESS_VIA_VPN_TUNNEL_UNSUPPORTED = 47 - NO_EXTERNAL_ADDRESS = 9 - UNKNOWN_INTERNAL_ADDRESS = 10 - FORWARDING_RULE_MISMATCH = 11 - FORWARDING_RULE_NO_INSTANCES = 12 - FIREWALL_BLOCKING_LOAD_BALANCER_BACKEND_HEALTH_CHECK = 13 - INSTANCE_NOT_RUNNING = 14 - GKE_CLUSTER_NOT_RUNNING = 27 - CLOUD_SQL_INSTANCE_NOT_RUNNING = 28 - REDIS_INSTANCE_NOT_RUNNING = 68 - REDIS_CLUSTER_NOT_RUNNING = 69 - TRAFFIC_TYPE_BLOCKED = 15 - GKE_MASTER_UNAUTHORIZED_ACCESS = 16 - CLOUD_SQL_INSTANCE_UNAUTHORIZED_ACCESS = 17 - DROPPED_INSIDE_GKE_SERVICE = 18 - DROPPED_INSIDE_CLOUD_SQL_SERVICE = 19 - GOOGLE_MANAGED_SERVICE_NO_PEERING = 20 - GOOGLE_MANAGED_SERVICE_NO_PSC_ENDPOINT = 38 - GKE_PSC_ENDPOINT_MISSING = 36 - CLOUD_SQL_INSTANCE_NO_IP_ADDRESS = 21 - GKE_CONTROL_PLANE_REGION_MISMATCH = 30 - PUBLIC_GKE_CONTROL_PLANE_TO_PRIVATE_DESTINATION = 31 - GKE_CONTROL_PLANE_NO_ROUTE = 32 - CLOUD_SQL_INSTANCE_NOT_CONFIGURED_FOR_EXTERNAL_TRAFFIC = 33 - PUBLIC_CLOUD_SQL_INSTANCE_TO_PRIVATE_DESTINATION = 34 - CLOUD_SQL_INSTANCE_NO_ROUTE = 35 - CLOUD_SQL_CONNECTOR_REQUIRED = 63 - CLOUD_FUNCTION_NOT_ACTIVE = 22 - VPC_CONNECTOR_NOT_SET = 23 - VPC_CONNECTOR_NOT_RUNNING = 24 - VPC_CONNECTOR_SERVERLESS_TRAFFIC_BLOCKED = 60 - VPC_CONNECTOR_HEALTH_CHECK_TRAFFIC_BLOCKED = 61 - FORWARDING_RULE_REGION_MISMATCH = 25 - PSC_CONNECTION_NOT_ACCEPTED = 26 - PSC_ENDPOINT_ACCESSED_FROM_PEERED_NETWORK = 41 - PSC_NEG_PRODUCER_ENDPOINT_NO_GLOBAL_ACCESS = 48 - PSC_NEG_PRODUCER_FORWARDING_RULE_MULTIPLE_PORTS = 54 - CLOUD_SQL_PSC_NEG_UNSUPPORTED = 58 - NO_NAT_SUBNETS_FOR_PSC_SERVICE_ATTACHMENT = 57 - PSC_TRANSITIVITY_NOT_PROPAGATED = 64 - HYBRID_NEG_NON_DYNAMIC_ROUTE_MATCHED = 55 - HYBRID_NEG_NON_LOCAL_DYNAMIC_ROUTE_MATCHED = 56 - CLOUD_RUN_REVISION_NOT_READY = 29 - DROPPED_INSIDE_PSC_SERVICE_PRODUCER = 37 - LOAD_BALANCER_HAS_NO_PROXY_SUBNET = 39 - CLOUD_NAT_NO_ADDRESSES = 40 - ROUTING_LOOP = 59 - DROPPED_INSIDE_GOOGLE_MANAGED_SERVICE = 62 - LOAD_BALANCER_BACKEND_INVALID_NETWORK = 65 - BACKEND_SERVICE_NAMED_PORT_NOT_DEFINED = 66 - DESTINATION_IS_PRIVATE_NAT_IP_RANGE = 67 - DROPPED_INSIDE_REDIS_INSTANCE_SERVICE = 70 - REDIS_INSTANCE_UNSUPPORTED_PORT = 71 - REDIS_INSTANCE_CONNECTING_FROM_PUPI_ADDRESS = 72 - REDIS_INSTANCE_NO_ROUTE_TO_DESTINATION_NETWORK = 73 - REDIS_INSTANCE_NO_EXTERNAL_IP = 74 - REDIS_INSTANCE_UNSUPPORTED_PROTOCOL = 78 - DROPPED_INSIDE_REDIS_CLUSTER_SERVICE = 75 - REDIS_CLUSTER_UNSUPPORTED_PORT = 76 - REDIS_CLUSTER_NO_EXTERNAL_IP = 77 - REDIS_CLUSTER_UNSUPPORTED_PROTOCOL = 79 - NO_ADVERTISED_ROUTE_TO_GCP_DESTINATION = 80 - NO_TRAFFIC_SELECTOR_TO_GCP_DESTINATION = 81 - NO_KNOWN_ROUTE_FROM_PEERED_NETWORK_TO_DESTINATION = 82 - PRIVATE_NAT_TO_PSC_ENDPOINT_UNSUPPORTED = 83 - - cause: Cause = proto.Field( - proto.ENUM, - number=1, - enum=Cause, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=2, - ) - source_ip: str = proto.Field( - proto.STRING, - number=3, - ) - destination_ip: str = proto.Field( - proto.STRING, - number=4, - ) - region: str = proto.Field( - proto.STRING, - number=5, - ) - - -class GKEMasterInfo(proto.Message): - r"""For display only. Metadata associated with a Google - Kubernetes Engine (GKE) cluster master. - - Attributes: - cluster_uri (str): - URI of a GKE cluster. - cluster_network_uri (str): - URI of a GKE cluster network. - internal_ip (str): - Internal IP address of a GKE cluster control - plane. - external_ip (str): - External IP address of a GKE cluster control - plane. - dns_endpoint (str): - DNS endpoint of a GKE cluster control plane. - """ - - cluster_uri: str = proto.Field( - proto.STRING, - number=2, - ) - cluster_network_uri: str = proto.Field( - proto.STRING, - number=4, - ) - internal_ip: str = proto.Field( - proto.STRING, - number=5, - ) - external_ip: str = proto.Field( - proto.STRING, - number=6, - ) - dns_endpoint: str = proto.Field( - proto.STRING, - number=7, - ) - - -class CloudSQLInstanceInfo(proto.Message): - r"""For display only. Metadata associated with a Cloud SQL - instance. - - Attributes: - display_name (str): - Name of a Cloud SQL instance. - uri (str): - URI of a Cloud SQL instance. - network_uri (str): - URI of a Cloud SQL instance network or empty - string if the instance does not have one. - internal_ip (str): - Internal IP address of a Cloud SQL instance. - external_ip (str): - External IP address of a Cloud SQL instance. - region (str): - Region in which the Cloud SQL instance is - running. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - network_uri: str = proto.Field( - proto.STRING, - number=4, - ) - internal_ip: str = proto.Field( - proto.STRING, - number=5, - ) - external_ip: str = proto.Field( - proto.STRING, - number=6, - ) - region: str = proto.Field( - proto.STRING, - number=7, - ) - - -class RedisInstanceInfo(proto.Message): - r"""For display only. Metadata associated with a Cloud Redis - Instance. - - Attributes: - display_name (str): - Name of a Cloud Redis Instance. - uri (str): - URI of a Cloud Redis Instance. - network_uri (str): - URI of a Cloud Redis Instance network. - primary_endpoint_ip (str): - Primary endpoint IP address of a Cloud Redis - Instance. - read_endpoint_ip (str): - Read endpoint IP address of a Cloud Redis - Instance (if applicable). - region (str): - Region in which the Cloud Redis Instance is - defined. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - network_uri: str = proto.Field( - proto.STRING, - number=3, - ) - primary_endpoint_ip: str = proto.Field( - proto.STRING, - number=4, - ) - read_endpoint_ip: str = proto.Field( - proto.STRING, - number=5, - ) - region: str = proto.Field( - proto.STRING, - number=6, - ) - - -class RedisClusterInfo(proto.Message): - r"""For display only. Metadata associated with a Redis Cluster. - - Attributes: - display_name (str): - Name of a Redis Cluster. - uri (str): - URI of a Redis Cluster in format - "projects/{project_id}/locations/{location}/clusters/{cluster_id}". - network_uri (str): - URI of a Redis Cluster network in format - "projects/{project_id}/global/networks/{network_id}". - discovery_endpoint_ip_address (str): - Discovery endpoint IP address of a Redis - Cluster. - secondary_endpoint_ip_address (str): - Secondary endpoint IP address of a Redis - Cluster. - location (str): - Name of the region in which the Redis Cluster - is defined. For example, "us-central1". - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - network_uri: str = proto.Field( - proto.STRING, - number=3, - ) - discovery_endpoint_ip_address: str = proto.Field( - proto.STRING, - number=4, - ) - secondary_endpoint_ip_address: str = proto.Field( - proto.STRING, - number=5, - ) - location: str = proto.Field( - proto.STRING, - number=6, - ) - - -class CloudFunctionInfo(proto.Message): - r"""For display only. Metadata associated with a Cloud Function. - - Attributes: - display_name (str): - Name of a Cloud Function. - uri (str): - URI of a Cloud Function. - location (str): - Location in which the Cloud Function is - deployed. - version_id (int): - Latest successfully deployed version id of - the Cloud Function. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - location: str = proto.Field( - proto.STRING, - number=3, - ) - version_id: int = proto.Field( - proto.INT64, - number=4, - ) - - -class CloudRunRevisionInfo(proto.Message): - r"""For display only. Metadata associated with a Cloud Run - revision. - - Attributes: - display_name (str): - Name of a Cloud Run revision. - uri (str): - URI of a Cloud Run revision. - location (str): - Location in which this revision is deployed. - service_uri (str): - URI of Cloud Run service this revision - belongs to. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - location: str = proto.Field( - proto.STRING, - number=4, - ) - service_uri: str = proto.Field( - proto.STRING, - number=5, - ) - - -class AppEngineVersionInfo(proto.Message): - r"""For display only. Metadata associated with an App Engine - version. - - Attributes: - display_name (str): - Name of an App Engine version. - uri (str): - URI of an App Engine version. - runtime (str): - Runtime of the App Engine version. - environment (str): - App Engine execution environment for a - version. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - runtime: str = proto.Field( - proto.STRING, - number=3, - ) - environment: str = proto.Field( - proto.STRING, - number=4, - ) - - -class VpcConnectorInfo(proto.Message): - r"""For display only. Metadata associated with a VPC connector. - - Attributes: - display_name (str): - Name of a VPC connector. - uri (str): - URI of a VPC connector. - location (str): - Location in which the VPC connector is - deployed. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - location: str = proto.Field( - proto.STRING, - number=3, - ) - - -class NatInfo(proto.Message): - r"""For display only. Metadata associated with NAT. - - Attributes: - type_ (google.cloud.network_management_v1.types.NatInfo.Type): - Type of NAT. - protocol (str): - IP protocol in string format, for example: - "TCP", "UDP", "ICMP". - network_uri (str): - URI of the network where NAT translation - takes place. - old_source_ip (str): - Source IP address before NAT translation. - new_source_ip (str): - Source IP address after NAT translation. - old_destination_ip (str): - Destination IP address before NAT - translation. - new_destination_ip (str): - Destination IP address after NAT translation. - old_source_port (int): - Source port before NAT translation. Only - valid when protocol is TCP or UDP. - new_source_port (int): - Source port after NAT translation. Only valid - when protocol is TCP or UDP. - old_destination_port (int): - Destination port before NAT translation. Only - valid when protocol is TCP or UDP. - new_destination_port (int): - Destination port after NAT translation. Only - valid when protocol is TCP or UDP. - router_uri (str): - Uri of the Cloud Router. Only valid when type is CLOUD_NAT. - nat_gateway_name (str): - The name of Cloud NAT Gateway. Only valid when type is - CLOUD_NAT. - """ - class Type(proto.Enum): - r"""Types of NAT. - - Values: - TYPE_UNSPECIFIED (0): - Type is unspecified. - INTERNAL_TO_EXTERNAL (1): - From Compute Engine instance's internal - address to external address. - EXTERNAL_TO_INTERNAL (2): - From Compute Engine instance's external - address to internal address. - CLOUD_NAT (3): - Cloud NAT Gateway. - PRIVATE_SERVICE_CONNECT (4): - Private service connect NAT. - """ - TYPE_UNSPECIFIED = 0 - INTERNAL_TO_EXTERNAL = 1 - EXTERNAL_TO_INTERNAL = 2 - CLOUD_NAT = 3 - PRIVATE_SERVICE_CONNECT = 4 - - type_: Type = proto.Field( - proto.ENUM, - number=1, - enum=Type, - ) - protocol: str = proto.Field( - proto.STRING, - number=2, - ) - network_uri: str = proto.Field( - proto.STRING, - number=3, - ) - old_source_ip: str = proto.Field( - proto.STRING, - number=4, - ) - new_source_ip: str = proto.Field( - proto.STRING, - number=5, - ) - old_destination_ip: str = proto.Field( - proto.STRING, - number=6, - ) - new_destination_ip: str = proto.Field( - proto.STRING, - number=7, - ) - old_source_port: int = proto.Field( - proto.INT32, - number=8, - ) - new_source_port: int = proto.Field( - proto.INT32, - number=9, - ) - old_destination_port: int = proto.Field( - proto.INT32, - number=10, - ) - new_destination_port: int = proto.Field( - proto.INT32, - number=11, - ) - router_uri: str = proto.Field( - proto.STRING, - number=12, - ) - nat_gateway_name: str = proto.Field( - proto.STRING, - number=13, - ) - - -class ProxyConnectionInfo(proto.Message): - r"""For display only. Metadata associated with ProxyConnection. - - Attributes: - protocol (str): - IP protocol in string format, for example: - "TCP", "UDP", "ICMP". - old_source_ip (str): - Source IP address of an original connection. - new_source_ip (str): - Source IP address of a new connection. - old_destination_ip (str): - Destination IP address of an original - connection - new_destination_ip (str): - Destination IP address of a new connection. - old_source_port (int): - Source port of an original connection. Only - valid when protocol is TCP or UDP. - new_source_port (int): - Source port of a new connection. Only valid - when protocol is TCP or UDP. - old_destination_port (int): - Destination port of an original connection. - Only valid when protocol is TCP or UDP. - new_destination_port (int): - Destination port of a new connection. Only - valid when protocol is TCP or UDP. - subnet_uri (str): - Uri of proxy subnet. - network_uri (str): - URI of the network where connection is - proxied. - """ - - protocol: str = proto.Field( - proto.STRING, - number=1, - ) - old_source_ip: str = proto.Field( - proto.STRING, - number=2, - ) - new_source_ip: str = proto.Field( - proto.STRING, - number=3, - ) - old_destination_ip: str = proto.Field( - proto.STRING, - number=4, - ) - new_destination_ip: str = proto.Field( - proto.STRING, - number=5, - ) - old_source_port: int = proto.Field( - proto.INT32, - number=6, - ) - new_source_port: int = proto.Field( - proto.INT32, - number=7, - ) - old_destination_port: int = proto.Field( - proto.INT32, - number=8, - ) - new_destination_port: int = proto.Field( - proto.INT32, - number=9, - ) - subnet_uri: str = proto.Field( - proto.STRING, - number=10, - ) - network_uri: str = proto.Field( - proto.STRING, - number=11, - ) - - -class LoadBalancerBackendInfo(proto.Message): - r"""For display only. Metadata associated with the load balancer - backend. - - Attributes: - name (str): - Display name of the backend. For example, it - might be an instance name for the instance group - backends, or an IP address and port for zonal - network endpoint group backends. - instance_uri (str): - URI of the backend instance (if applicable). - Populated for instance group backends, and zonal - NEG backends. - backend_service_uri (str): - URI of the backend service this backend - belongs to (if applicable). - instance_group_uri (str): - URI of the instance group this backend - belongs to (if applicable). - network_endpoint_group_uri (str): - URI of the network endpoint group this - backend belongs to (if applicable). - backend_bucket_uri (str): - URI of the backend bucket this backend - targets (if applicable). - psc_service_attachment_uri (str): - URI of the PSC service attachment this PSC - NEG backend targets (if applicable). - psc_google_api_target (str): - PSC Google API target this PSC NEG backend - targets (if applicable). - health_check_uri (str): - URI of the health check attached to this - backend (if applicable). - health_check_firewalls_config_state (google.cloud.network_management_v1.types.LoadBalancerBackendInfo.HealthCheckFirewallsConfigState): - Output only. Health check firewalls - configuration state for the backend. This is a - result of the static firewall analysis - (verifying that health check traffic from - required IP ranges to the backend is allowed or - not). The backend might still be unhealthy even - if these firewalls are configured. Please refer - to the documentation for more information: - - https://cloud.google.com/load-balancing/docs/firewall-rules - """ - class HealthCheckFirewallsConfigState(proto.Enum): - r"""Health check firewalls configuration state enum. - - Values: - HEALTH_CHECK_FIREWALLS_CONFIG_STATE_UNSPECIFIED (0): - Configuration state unspecified. It usually - means that the backend has no health check - attached, or there was an unexpected - configuration error preventing Connectivity - tests from verifying health check configuration. - FIREWALLS_CONFIGURED (1): - Firewall rules (policies) allowing health - check traffic from all required IP ranges to the - backend are configured. - FIREWALLS_PARTIALLY_CONFIGURED (2): - Firewall rules (policies) allow health check - traffic only from a part of required IP ranges. - FIREWALLS_NOT_CONFIGURED (3): - Firewall rules (policies) deny health check - traffic from all required IP ranges to the - backend. - FIREWALLS_UNSUPPORTED (4): - The network contains firewall rules of - unsupported types, so Connectivity tests were - not able to verify health check configuration - status. Please refer to the documentation for - the list of unsupported configurations: - - https://cloud.google.com/network-intelligence-center/docs/connectivity-tests/concepts/overview#unsupported-configs - """ - HEALTH_CHECK_FIREWALLS_CONFIG_STATE_UNSPECIFIED = 0 - FIREWALLS_CONFIGURED = 1 - FIREWALLS_PARTIALLY_CONFIGURED = 2 - FIREWALLS_NOT_CONFIGURED = 3 - FIREWALLS_UNSUPPORTED = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - instance_uri: str = proto.Field( - proto.STRING, - number=2, - ) - backend_service_uri: str = proto.Field( - proto.STRING, - number=3, - ) - instance_group_uri: str = proto.Field( - proto.STRING, - number=4, - ) - network_endpoint_group_uri: str = proto.Field( - proto.STRING, - number=5, - ) - backend_bucket_uri: str = proto.Field( - proto.STRING, - number=8, - ) - psc_service_attachment_uri: str = proto.Field( - proto.STRING, - number=9, - ) - psc_google_api_target: str = proto.Field( - proto.STRING, - number=10, - ) - health_check_uri: str = proto.Field( - proto.STRING, - number=6, - ) - health_check_firewalls_config_state: HealthCheckFirewallsConfigState = proto.Field( - proto.ENUM, - number=7, - enum=HealthCheckFirewallsConfigState, - ) - - -class StorageBucketInfo(proto.Message): - r"""For display only. Metadata associated with Storage Bucket. - - Attributes: - bucket (str): - Cloud Storage Bucket name. - """ - - bucket: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ServerlessNegInfo(proto.Message): - r"""For display only. Metadata associated with the serverless - network endpoint group backend. - - Attributes: - neg_uri (str): - URI of the serverless network endpoint group. - """ - - neg_uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/mypy.ini b/owl-bot-staging/google-cloud-network-management/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-management/v1/noxfile.py b/owl-bot-staging/google-cloud-network-management/v1/noxfile.py deleted file mode 100644 index e09f07364b34..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-network-management' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/network_management_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/network_management_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-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py deleted file mode 100644 index c74b86142f00..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_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 CreateConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_create_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.CreateConnectivityTestRequest( - parent="parent_value", - test_id="test_id_value", - ) - - # Make the request - operation = client.create_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py deleted file mode 100644 index c27c11cc246a..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_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 CreateConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_create_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.CreateConnectivityTestRequest( - parent="parent_value", - test_id="test_id_value", - ) - - # Make the request - operation = client.create_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py deleted file mode 100644 index cc7d4daf1552..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_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 DeleteConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_delete_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.DeleteConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py deleted file mode 100644 index 00d6602a4aef..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_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 DeleteConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_delete_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.DeleteConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py deleted file mode 100644 index 85b70752cf16..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_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 GetConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_get_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.GetConnectivityTestRequest( - name="name_value", - ) - - # Make the request - response = await client.get_connectivity_test(request=request) - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py deleted file mode 100644 index 40673d28a839..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_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 GetConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_get_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.GetConnectivityTestRequest( - name="name_value", - ) - - # Make the request - response = client.get_connectivity_test(request=request) - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py deleted file mode 100644 index 15d2f1f0232f..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_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 ListConnectivityTests -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_list_connectivity_tests(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.ListConnectivityTestsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_connectivity_tests(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py deleted file mode 100644 index c595e917f169..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_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 ListConnectivityTests -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_list_connectivity_tests(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.ListConnectivityTestsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_connectivity_tests(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py deleted file mode 100644 index 9ba7e4c6759f..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_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 RerunConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_rerun_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.RerunConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.rerun_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py deleted file mode 100644 index c726b18eda73..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_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 RerunConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_rerun_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.RerunConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.rerun_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py deleted file mode 100644 index a89f65bf0aa0..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_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 UpdateConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_update_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.UpdateConnectivityTestRequest( - ) - - # Make the request - operation = client.update_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py deleted file mode 100644 index 503f72cf246b..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_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 UpdateConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_update_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.UpdateConnectivityTestRequest( - ) - - # Make the request - operation = client.update_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json deleted file mode 100644 index a6a39ec02f7f..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json +++ /dev/null @@ -1,997 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.networkmanagement.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-network-management", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.create_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.CreateConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "CreateConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.CreateConnectivityTestRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "test_id", - "type": "str" - }, - { - "name": "resource", - "type": "google.cloud.network_management_v1.types.ConnectivityTest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for CreateConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.create_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.CreateConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "CreateConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.CreateConnectivityTestRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "test_id", - "type": "str" - }, - { - "name": "resource", - "type": "google.cloud.network_management_v1.types.ConnectivityTest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for CreateConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.delete_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.DeleteConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "DeleteConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.DeleteConnectivityTestRequest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for DeleteConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.delete_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.DeleteConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "DeleteConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.DeleteConnectivityTestRequest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for DeleteConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.get_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.GetConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "GetConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.GetConnectivityTestRequest" - }, - { - "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.network_management_v1.types.ConnectivityTest", - "shortName": "get_connectivity_test" - }, - "description": "Sample for GetConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.get_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.GetConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "GetConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.GetConnectivityTestRequest" - }, - { - "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.network_management_v1.types.ConnectivityTest", - "shortName": "get_connectivity_test" - }, - "description": "Sample for GetConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.list_connectivity_tests", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.ListConnectivityTests", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "ListConnectivityTests" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.ListConnectivityTestsRequest" - }, - { - "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.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsAsyncPager", - "shortName": "list_connectivity_tests" - }, - "description": "Sample for ListConnectivityTests", - "file": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_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": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.list_connectivity_tests", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.ListConnectivityTests", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "ListConnectivityTests" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.ListConnectivityTestsRequest" - }, - { - "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.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsPager", - "shortName": "list_connectivity_tests" - }, - "description": "Sample for ListConnectivityTests", - "file": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_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": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.rerun_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.RerunConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "RerunConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.RerunConnectivityTestRequest" - }, - { - "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": "rerun_connectivity_test" - }, - "description": "Sample for RerunConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.rerun_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.RerunConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "RerunConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.RerunConnectivityTestRequest" - }, - { - "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": "rerun_connectivity_test" - }, - "description": "Sample for RerunConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.update_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.UpdateConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "UpdateConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.UpdateConnectivityTestRequest" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "resource", - "type": "google.cloud.network_management_v1.types.ConnectivityTest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for UpdateConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.update_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.UpdateConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "UpdateConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.UpdateConnectivityTestRequest" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "resource", - "type": "google.cloud.network_management_v1.types.ConnectivityTest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for UpdateConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py b/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py deleted file mode 100644 index 33791cd81e72..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py +++ /dev/null @@ -1,181 +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 network_managementCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_connectivity_test': ('parent', 'test_id', 'resource', ), - 'delete_connectivity_test': ('name', ), - 'get_connectivity_test': ('name', ), - 'list_connectivity_tests': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'rerun_connectivity_test': ('name', ), - 'update_connectivity_test': ('update_mask', 'resource', ), - } - - 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=network_managementCallTransformer(), -): - """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 network_management 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-network-management/v1/setup.py b/owl-bot-staging/google-cloud-network-management/v1/setup.py deleted file mode 100644 index 110a46599b9a..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-network-management' - - -description = "Google Cloud Network Management API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/network_management/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-management" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_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-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py deleted file mode 100644 index 00328a587e68..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py +++ /dev/null @@ -1,7462 +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.location import locations_pb2 -from google.cloud.network_management_v1.services.reachability_service import ReachabilityServiceAsyncClient -from google.cloud.network_management_v1.services.reachability_service import ReachabilityServiceClient -from google.cloud.network_management_v1.services.reachability_service import pagers -from google.cloud.network_management_v1.services.reachability_service import transports -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.cloud.network_management_v1.types import trace -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import 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 ReachabilityServiceClient._get_default_mtls_endpoint(None) is None - assert ReachabilityServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ReachabilityServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ReachabilityServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ReachabilityServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ReachabilityServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ReachabilityServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ReachabilityServiceClient._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 ReachabilityServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ReachabilityServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ReachabilityServiceClient._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 ReachabilityServiceClient._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 ReachabilityServiceClient._get_client_cert_source(None, False) is None - assert ReachabilityServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ReachabilityServiceClient._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 ReachabilityServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ReachabilityServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) -@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ReachabilityServiceClient._DEFAULT_UNIVERSE - default_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ReachabilityServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ReachabilityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT - assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "always") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT - assert ReachabilityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT - assert ReachabilityServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ReachabilityServiceClient._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 ReachabilityServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ReachabilityServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ReachabilityServiceClient._get_universe_domain(None, None) == ReachabilityServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ReachabilityServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ReachabilityServiceClient, "grpc"), - (ReachabilityServiceAsyncClient, "grpc_asyncio"), - (ReachabilityServiceClient, "rest"), -]) -def test_reachability_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'networkmanagement.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networkmanagement.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ReachabilityServiceGrpcTransport, "grpc"), - (transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ReachabilityServiceRestTransport, "rest"), -]) -def test_reachability_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ReachabilityServiceClient, "grpc"), - (ReachabilityServiceAsyncClient, "grpc_asyncio"), - (ReachabilityServiceClient, "rest"), -]) -def test_reachability_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'networkmanagement.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networkmanagement.googleapis.com' - ) - - -def test_reachability_service_client_get_transport_class(): - transport = ReachabilityServiceClient.get_transport_class() - available_transports = [ - transports.ReachabilityServiceGrpcTransport, - transports.ReachabilityServiceRestTransport, - ] - assert transport in available_transports - - transport = ReachabilityServiceClient.get_transport_class("grpc") - assert transport == transports.ReachabilityServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc"), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest"), -]) -@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) -@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) -def test_reachability_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(ReachabilityServiceClient, '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(ReachabilityServiceClient, '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", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", "true"), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", "false"), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", "true"), - (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) -@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_reachability_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ReachabilityServiceClient, ReachabilityServiceAsyncClient -]) -@mock.patch.object(ReachabilityServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReachabilityServiceClient)) -@mock.patch.object(ReachabilityServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReachabilityServiceAsyncClient)) -def test_reachability_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_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", [ - ReachabilityServiceClient, ReachabilityServiceAsyncClient -]) -@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) -@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) -def test_reachability_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ReachabilityServiceClient._DEFAULT_UNIVERSE - default_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ReachabilityServiceClient._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", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc"), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest"), -]) -def test_reachability_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", grpc_helpers), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", None), -]) -def test_reachability_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_reachability_service_client_client_options_from_dict(): - with mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ReachabilityServiceClient( - 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", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", grpc_helpers), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_reachability_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "networkmanagement.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="networkmanagement.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - reachability.ListConnectivityTestsRequest, - dict, -]) -def test_list_connectivity_tests(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_connectivity_tests), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = reachability.ListConnectivityTestsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.ListConnectivityTestsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConnectivityTestsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_connectivity_tests_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 = ReachabilityServiceClient( - 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 = reachability.ListConnectivityTestsRequest( - 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_connectivity_tests), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_connectivity_tests(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.ListConnectivityTestsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_connectivity_tests_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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_connectivity_tests in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_tests] = mock_rpc - request = {} - client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_connectivity_tests(request) - - # Establish that a new wrapper 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_connectivity_tests_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 = ReachabilityServiceAsyncClient( - 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_connectivity_tests 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_connectivity_tests] = mock_rpc - - request = {} - await client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_connectivity_tests(request) - - # Establish that a new wrapper 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_connectivity_tests_async(transport: str = 'grpc_asyncio', request_type=reachability.ListConnectivityTestsRequest): - client = ReachabilityServiceAsyncClient( - 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_connectivity_tests), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.ListConnectivityTestsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConnectivityTestsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_connectivity_tests_async_from_dict(): - await test_list_connectivity_tests_async(request_type=dict) - -def test_list_connectivity_tests_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.ListConnectivityTestsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - call.return_value = reachability.ListConnectivityTestsResponse() - client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_connectivity_tests_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.ListConnectivityTestsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse()) - await client.list_connectivity_tests(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_connectivity_tests_flattened(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = reachability.ListConnectivityTestsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_connectivity_tests( - 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_connectivity_tests_flattened_error(): - client = ReachabilityServiceClient( - 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_connectivity_tests( - reachability.ListConnectivityTestsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_connectivity_tests_flattened_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = reachability.ListConnectivityTestsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_connectivity_tests( - 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_connectivity_tests_flattened_error_async(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_tests( - reachability.ListConnectivityTestsRequest(), - parent='parent_value', - ) - - -def test_list_connectivity_tests_pager(transport_name: str = "grpc"): - client = ReachabilityServiceClient( - 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_connectivity_tests), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - next_page_token='abc', - ), - reachability.ListConnectivityTestsResponse( - resources=[], - next_page_token='def', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - ], - next_page_token='ghi', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_connectivity_tests(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, connectivity_test.ConnectivityTest) - for i in results) -def test_list_connectivity_tests_pages(transport_name: str = "grpc"): - client = ReachabilityServiceClient( - 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_connectivity_tests), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - next_page_token='abc', - ), - reachability.ListConnectivityTestsResponse( - resources=[], - next_page_token='def', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - ], - next_page_token='ghi', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - ), - RuntimeError, - ) - pages = list(client.list_connectivity_tests(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_connectivity_tests_async_pager(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - next_page_token='abc', - ), - reachability.ListConnectivityTestsResponse( - resources=[], - next_page_token='def', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - ], - next_page_token='ghi', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_connectivity_tests(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, connectivity_test.ConnectivityTest) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_connectivity_tests_async_pages(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - next_page_token='abc', - ), - reachability.ListConnectivityTestsResponse( - resources=[], - next_page_token='def', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - ], - next_page_token='ghi', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - ), - 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_connectivity_tests(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", [ - reachability.GetConnectivityTestRequest, - dict, -]) -def test_get_connectivity_test(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = connectivity_test.ConnectivityTest( - name='name_value', - description='description_value', - protocol='protocol_value', - related_projects=['related_projects_value'], - display_name='display_name_value', - bypass_firewall_checks=True, - ) - response = client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.GetConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, connectivity_test.ConnectivityTest) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.protocol == 'protocol_value' - assert response.related_projects == ['related_projects_value'] - assert response.display_name == 'display_name_value' - assert response.bypass_firewall_checks is True - - -def test_get_connectivity_test_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 = ReachabilityServiceClient( - 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 = reachability.GetConnectivityTestRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_connectivity_test(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.GetConnectivityTestRequest( - name='name_value', - ) - -def test_get_connectivity_test_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - request = {} - client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( - 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_connectivity_test 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_connectivity_test] = mock_rpc - - request = {} - await client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.GetConnectivityTestRequest): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest( - name='name_value', - description='description_value', - protocol='protocol_value', - related_projects=['related_projects_value'], - display_name='display_name_value', - bypass_firewall_checks=True, - )) - response = await client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.GetConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, connectivity_test.ConnectivityTest) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.protocol == 'protocol_value' - assert response.related_projects == ['related_projects_value'] - assert response.display_name == 'display_name_value' - assert response.bypass_firewall_checks is True - - -@pytest.mark.asyncio -async def test_get_connectivity_test_async_from_dict(): - await test_get_connectivity_test_async(request_type=dict) - -def test_get_connectivity_test_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.GetConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - call.return_value = connectivity_test.ConnectivityTest() - client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_connectivity_test_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.GetConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest()) - await client.get_connectivity_test(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_connectivity_test_flattened(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = connectivity_test.ConnectivityTest() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_connectivity_test( - 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_connectivity_test_flattened_error(): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.GetConnectivityTestRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_connectivity_test_flattened_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = connectivity_test.ConnectivityTest() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_connectivity_test( - 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_connectivity_test_flattened_error_async(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test( - reachability.GetConnectivityTestRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - reachability.CreateConnectivityTestRequest, - dict, -]) -def test_create_connectivity_test(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.CreateConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_connectivity_test_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 = ReachabilityServiceClient( - 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 = reachability.CreateConnectivityTestRequest( - parent='parent_value', - test_id='test_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_connectivity_test(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.CreateConnectivityTestRequest( - parent='parent_value', - test_id='test_id_value', - ) - -def test_create_connectivity_test_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - request = {} - client.create_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( - 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_connectivity_test 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_connectivity_test] = mock_rpc - - request = {} - await client.create_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.CreateConnectivityTestRequest): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test), - '__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_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.CreateConnectivityTestRequest() - 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_connectivity_test_async_from_dict(): - await test_create_connectivity_test_async(request_type=dict) - -def test_create_connectivity_test_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.CreateConnectivityTestRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_connectivity_test_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.CreateConnectivityTestRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_connectivity_test(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_connectivity_test_flattened(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__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_connectivity_test( - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].test_id - mock_val = 'test_id_value' - assert arg == mock_val - arg = args[0].resource - mock_val = connectivity_test.ConnectivityTest(name='name_value') - assert arg == mock_val - - -def test_create_connectivity_test_flattened_error(): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.CreateConnectivityTestRequest(), - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_connectivity_test_flattened_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__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_connectivity_test( - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].test_id - mock_val = 'test_id_value' - assert arg == mock_val - arg = args[0].resource - mock_val = connectivity_test.ConnectivityTest(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_connectivity_test_flattened_error_async(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test( - reachability.CreateConnectivityTestRequest(), - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - reachability.UpdateConnectivityTestRequest, - dict, -]) -def test_update_connectivity_test(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.UpdateConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_connectivity_test_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 = ReachabilityServiceClient( - 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 = reachability.UpdateConnectivityTestRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_connectivity_test(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.UpdateConnectivityTestRequest( - ) - -def test_update_connectivity_test_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - request = {} - client.update_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( - 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_connectivity_test 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_connectivity_test] = mock_rpc - - request = {} - await client.update_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.UpdateConnectivityTestRequest): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test), - '__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_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.UpdateConnectivityTestRequest() - 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_connectivity_test_async_from_dict(): - await test_update_connectivity_test_async(request_type=dict) - -def test_update_connectivity_test_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.UpdateConnectivityTestRequest() - - request.resource.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_connectivity_test_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.UpdateConnectivityTestRequest() - - request.resource.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource.name=name_value', - ) in kw['metadata'] - - -def test_update_connectivity_test_flattened(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__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_connectivity_test( - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(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].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - arg = args[0].resource - mock_val = connectivity_test.ConnectivityTest(name='name_value') - assert arg == mock_val - - -def test_update_connectivity_test_flattened_error(): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.UpdateConnectivityTestRequest(), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_connectivity_test_flattened_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__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_connectivity_test( - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(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].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - arg = args[0].resource - mock_val = connectivity_test.ConnectivityTest(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_connectivity_test_flattened_error_async(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test( - reachability.UpdateConnectivityTestRequest(), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - reachability.RerunConnectivityTestRequest, - dict, -]) -def test_rerun_connectivity_test(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rerun_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.RerunConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rerun_connectivity_test_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 = ReachabilityServiceClient( - 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 = reachability.RerunConnectivityTestRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.rerun_connectivity_test(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.RerunConnectivityTestRequest( - name='name_value', - ) - -def test_rerun_connectivity_test_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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.rerun_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.rerun_connectivity_test] = mock_rpc - request = {} - client.rerun_connectivity_test(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.rerun_connectivity_test(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_rerun_connectivity_test_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 = ReachabilityServiceAsyncClient( - 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.rerun_connectivity_test 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.rerun_connectivity_test] = mock_rpc - - request = {} - await client.rerun_connectivity_test(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.rerun_connectivity_test(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_rerun_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.RerunConnectivityTestRequest): - client = ReachabilityServiceAsyncClient( - 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.rerun_connectivity_test), - '__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.rerun_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.RerunConnectivityTestRequest() - 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_rerun_connectivity_test_async_from_dict(): - await test_rerun_connectivity_test_async(request_type=dict) - -def test_rerun_connectivity_test_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.RerunConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rerun_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_rerun_connectivity_test_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.RerunConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rerun_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - reachability.DeleteConnectivityTestRequest, - dict, -]) -def test_delete_connectivity_test(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.DeleteConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_connectivity_test_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 = ReachabilityServiceClient( - 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 = reachability.DeleteConnectivityTestRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_connectivity_test(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.DeleteConnectivityTestRequest( - name='name_value', - ) - -def test_delete_connectivity_test_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - request = {} - client.delete_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( - 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_connectivity_test 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_connectivity_test] = mock_rpc - - request = {} - await client.delete_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.DeleteConnectivityTestRequest): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test), - '__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_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.DeleteConnectivityTestRequest() - 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_connectivity_test_async_from_dict(): - await test_delete_connectivity_test_async(request_type=dict) - -def test_delete_connectivity_test_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.DeleteConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_connectivity_test_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.DeleteConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_connectivity_test(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_connectivity_test_flattened(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__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_connectivity_test( - 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_connectivity_test_flattened_error(): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.DeleteConnectivityTestRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_connectivity_test_flattened_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__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_connectivity_test( - 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_connectivity_test_flattened_error_async(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test( - reachability.DeleteConnectivityTestRequest(), - name='name_value', - ) - - -def test_list_connectivity_tests_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 = ReachabilityServiceClient( - 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_connectivity_tests in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_tests] = mock_rpc - - request = {} - client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_connectivity_tests(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_connectivity_tests_rest_required_fields(request_type=reachability.ListConnectivityTestsRequest): - transport_class = transports.ReachabilityServiceRestTransport - - 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_connectivity_tests._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_connectivity_tests._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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = reachability.ListConnectivityTestsResponse() - # Mock the http request call 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_connectivity_tests_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_connectivity_tests._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_connectivity_tests_rest_flattened(): - client = ReachabilityServiceClient( - 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 = reachability.ListConnectivityTestsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/global'} - - # 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(**mock_args) - - # Establish that the underlying call 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/global}/connectivityTests" % client.transport._host, args[1]) - - -def test_list_connectivity_tests_rest_flattened_error(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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_connectivity_tests( - reachability.ListConnectivityTestsRequest(), - parent='parent_value', - ) - - -def test_list_connectivity_tests_rest_pager(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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 = ( - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - next_page_token='abc', - ), - reachability.ListConnectivityTestsResponse( - resources=[], - next_page_token='def', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - ], - next_page_token='ghi', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(reachability.ListConnectivityTestsResponse.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/global'} - - pager = client.list_connectivity_tests(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, connectivity_test.ConnectivityTest) - for i in results) - - pages = list(client.list_connectivity_tests(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_connectivity_test_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 = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - - request = {} - client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.GetConnectivityTestRequest): - transport_class = transports.ReachabilityServiceRestTransport - - 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = connectivity_test.ConnectivityTest() - # Mock the http request call 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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_connectivity_test_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_connectivity_test._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_connectivity_test_rest_flattened(): - client = ReachabilityServiceClient( - 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 = connectivity_test.ConnectivityTest() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/global/connectivityTests/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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(**mock_args) - - # Establish that the underlying call 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/global/connectivityTests/*}" % client.transport._host, args[1]) - - -def test_get_connectivity_test_rest_flattened_error(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.GetConnectivityTestRequest(), - name='name_value', - ) - - -def test_create_connectivity_test_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 = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - - request = {} - client.create_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.CreateConnectivityTestRequest): - transport_class = transports.ReachabilityServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["test_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 "testId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_connectivity_test._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "testId" in jsonified_request - assert jsonified_request["testId"] == request_init["test_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["testId"] = 'test_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_connectivity_test._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("test_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 "testId" in jsonified_request - assert jsonified_request["testId"] == 'test_id_value' - - client = ReachabilityServiceClient( - 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_connectivity_test(request) - - expected_params = [ - ( - "testId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_connectivity_test_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_connectivity_test._get_unset_required_fields({}) - assert set(unset_fields) == (set(("testId", )) & set(("parent", "testId", "resource", ))) - - -def test_create_connectivity_test_rest_flattened(): - client = ReachabilityServiceClient( - 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/global'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(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.create_connectivity_test(**mock_args) - - # Establish that the underlying call 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/global}/connectivityTests" % client.transport._host, args[1]) - - -def test_create_connectivity_test_rest_flattened_error(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.CreateConnectivityTestRequest(), - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - -def test_update_connectivity_test_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 = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - - request = {} - client.update_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.UpdateConnectivityTestRequest): - transport_class = transports.ReachabilityServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_connectivity_test._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_connectivity_test._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_connectivity_test(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_connectivity_test_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_connectivity_test._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", "resource", ))) - - -def test_update_connectivity_test_rest_flattened(): - client = ReachabilityServiceClient( - 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 = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(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.update_connectivity_test(**mock_args) - - # Establish that the underlying call 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/{resource.name=projects/*/locations/global/connectivityTests/*}" % client.transport._host, args[1]) - - -def test_update_connectivity_test_rest_flattened_error(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.UpdateConnectivityTestRequest(), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - -def test_rerun_connectivity_test_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 = ReachabilityServiceClient( - 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.rerun_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.rerun_connectivity_test] = mock_rpc - - request = {} - client.rerun_connectivity_test(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.rerun_connectivity_test(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_rerun_connectivity_test_rest_required_fields(request_type=reachability.RerunConnectivityTestRequest): - transport_class = transports.ReachabilityServiceRestTransport - - 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()).rerun_connectivity_test._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()).rerun_connectivity_test._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 = ReachabilityServiceClient( - 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.rerun_connectivity_test(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_rerun_connectivity_test_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.rerun_connectivity_test._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_connectivity_test_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 = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - - request = {} - client.delete_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.DeleteConnectivityTestRequest): - transport_class = transports.ReachabilityServiceRestTransport - - 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( - 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_connectivity_test(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_connectivity_test_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_connectivity_test._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_connectivity_test_rest_flattened(): - client = ReachabilityServiceClient( - 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/global/connectivityTests/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_connectivity_test(**mock_args) - - # Establish that the underlying call 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/global/connectivityTests/*}" % client.transport._host, args[1]) - - -def test_delete_connectivity_test_rest_flattened_error(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.DeleteConnectivityTestRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ReachabilityServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ReachabilityServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ReachabilityServiceGrpcTransport, - transports.ReachabilityServiceGrpcAsyncIOTransport, - transports.ReachabilityServiceRestTransport, -]) -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 = ReachabilityServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ReachabilityServiceClient( - 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_connectivity_tests_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - call.return_value = reachability.ListConnectivityTestsResponse() - client.list_connectivity_tests(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.ListConnectivityTestsRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - call.return_value = connectivity_test.ConnectivityTest() - client.get_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.GetConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.CreateConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.UpdateConnectivityTestRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_rerun_connectivity_test_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rerun_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.RerunConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.DeleteConnectivityTestRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ReachabilityServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_tests_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_connectivity_tests(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.ListConnectivityTestsRequest() - - assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest( - name='name_value', - description='description_value', - protocol='protocol_value', - related_projects=['related_projects_value'], - display_name='display_name_value', - bypass_firewall_checks=True, - )) - await client.get_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.GetConnectivityTestRequest() - - assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__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_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.CreateConnectivityTestRequest() - - assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__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_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.UpdateConnectivityTestRequest() - - assert args[0] == request_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_rerun_connectivity_test_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__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.rerun_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.RerunConnectivityTestRequest() - - assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__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_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.DeleteConnectivityTestRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ReachabilityServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_connectivity_tests_rest_bad_request(request_type=reachability.ListConnectivityTestsRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/global'} - 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_connectivity_tests(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.ListConnectivityTestsRequest, - dict, -]) -def test_list_connectivity_tests_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/global'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = reachability.ListConnectivityTestsResponse( - 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConnectivityTestsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_connectivity_tests_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_list_connectivity_tests") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_list_connectivity_tests") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.ListConnectivityTestsRequest.pb(reachability.ListConnectivityTestsRequest()) - 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 = reachability.ListConnectivityTestsResponse.to_json(reachability.ListConnectivityTestsResponse()) - req.return_value.content = return_value - - request = reachability.ListConnectivityTestsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = reachability.ListConnectivityTestsResponse() - - client.list_connectivity_tests(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_connectivity_test_rest_bad_request(request_type=reachability.GetConnectivityTestRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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_connectivity_test(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.GetConnectivityTestRequest, - dict, -]) -def test_get_connectivity_test_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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 = connectivity_test.ConnectivityTest( - name='name_value', - description='description_value', - protocol='protocol_value', - related_projects=['related_projects_value'], - display_name='display_name_value', - bypass_firewall_checks=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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, connectivity_test.ConnectivityTest) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.protocol == 'protocol_value' - assert response.related_projects == ['related_projects_value'] - assert response.display_name == 'display_name_value' - assert response.bypass_firewall_checks is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_connectivity_test_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_get_connectivity_test") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_get_connectivity_test") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.GetConnectivityTestRequest.pb(reachability.GetConnectivityTestRequest()) - 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 = connectivity_test.ConnectivityTest.to_json(connectivity_test.ConnectivityTest()) - req.return_value.content = return_value - - request = reachability.GetConnectivityTestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = connectivity_test.ConnectivityTest() - - client.get_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_connectivity_test_rest_bad_request(request_type=reachability.CreateConnectivityTestRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/global'} - 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_connectivity_test(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.CreateConnectivityTestRequest, - dict, -]) -def test_create_connectivity_test_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/global'} - request_init["resource"] = {'name': 'name_value', 'description': 'description_value', 'source': {'ip_address': 'ip_address_value', 'port': 453, 'instance': 'instance_value', 'forwarding_rule': 'forwarding_rule_value', 'forwarding_rule_target': 1, 'load_balancer_id': 'load_balancer_id_value', 'load_balancer_type': 1, 'gke_master_cluster': 'gke_master_cluster_value', 'fqdn': 'fqdn_value', 'cloud_sql_instance': 'cloud_sql_instance_value', 'redis_instance': 'redis_instance_value', 'redis_cluster': 'redis_cluster_value', 'cloud_function': {'uri': 'uri_value'}, 'app_engine_version': {'uri': 'uri_value'}, 'cloud_run_revision': {'uri': 'uri_value'}, 'network': 'network_value', 'network_type': 1, 'project_id': 'project_id_value'}, 'destination': {}, 'protocol': 'protocol_value', 'related_projects': ['related_projects_value1', 'related_projects_value2'], 'display_name': 'display_name_value', 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'reachability_details': {'result': 1, 'verify_time': {}, 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'traces': [{'endpoint_info': {'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'protocol': 'protocol_value', 'source_port': 1205, 'destination_port': 1734, 'source_network_uri': 'source_network_uri_value', 'destination_network_uri': 'destination_network_uri_value', 'source_agent_uri': 'source_agent_uri_value'}, 'steps': [{'description': 'description_value', 'state': 1, 'causes_drop': True, 'project_id': 'project_id_value', 'instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'interface': 'interface_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'network_tags': ['network_tags_value1', 'network_tags_value2'], 'service_account': 'service_account_value', 'psc_network_attachment_uri': 'psc_network_attachment_uri_value'}, 'firewall': {'display_name': 'display_name_value', 'uri': 'uri_value', 'direction': 'direction_value', 'action': 'action_value', 'priority': 898, 'network_uri': 'network_uri_value', 'target_tags': ['target_tags_value1', 'target_tags_value2'], 'target_service_accounts': ['target_service_accounts_value1', 'target_service_accounts_value2'], 'policy': 'policy_value', 'policy_uri': 'policy_uri_value', 'firewall_rule_type': 1}, 'route': {'route_type': 1, 'next_hop_type': 1, 'route_scope': 1, 'display_name': 'display_name_value', 'uri': 'uri_value', 'region': 'region_value', 'dest_ip_range': 'dest_ip_range_value', 'next_hop': 'next_hop_value', 'network_uri': 'network_uri_value', 'priority': 898, 'instance_tags': ['instance_tags_value1', 'instance_tags_value2'], 'src_ip_range': 'src_ip_range_value', 'dest_port_ranges': ['dest_port_ranges_value1', 'dest_port_ranges_value2'], 'src_port_ranges': ['src_port_ranges_value1', 'src_port_ranges_value2'], 'protocols': ['protocols_value1', 'protocols_value2'], 'ncc_hub_uri': 'ncc_hub_uri_value', 'ncc_spoke_uri': 'ncc_spoke_uri_value', 'advertised_route_source_router_uri': 'advertised_route_source_router_uri_value', 'advertised_route_next_hop_uri': 'advertised_route_next_hop_uri_value'}, 'endpoint': {}, 'google_service': {'source_ip': 'source_ip_value', 'google_service_type': 1}, 'forwarding_rule': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_protocol': 'matched_protocol_value', 'matched_port_range': 'matched_port_range_value', 'vip': 'vip_value', 'target': 'target_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'load_balancer_name': 'load_balancer_name_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'vpn_gateway': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'ip_address': 'ip_address_value', 'vpn_tunnel_uri': 'vpn_tunnel_uri_value', 'region': 'region_value'}, 'vpn_tunnel': {'display_name': 'display_name_value', 'uri': 'uri_value', 'source_gateway': 'source_gateway_value', 'remote_gateway': 'remote_gateway_value', 'remote_gateway_ip': 'remote_gateway_ip_value', 'source_gateway_ip': 'source_gateway_ip_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'routing_type': 1}, 'vpc_connector': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value'}, 'deliver': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'storage_bucket': 'storage_bucket_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'forward': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value'}, 'abort': {'cause': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'projects_missing_permission': ['projects_missing_permission_value1', 'projects_missing_permission_value2']}, 'drop': {'cause': 1, 'resource_uri': 'resource_uri_value', 'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'region': 'region_value'}, 'load_balancer': {'load_balancer_type': 1, 'health_check_uri': 'health_check_uri_value', 'backends': [{'display_name': 'display_name_value', 'uri': 'uri_value', 'health_check_firewall_state': 1, 'health_check_allowing_firewall_rules': ['health_check_allowing_firewall_rules_value1', 'health_check_allowing_firewall_rules_value2'], 'health_check_blocking_firewall_rules': ['health_check_blocking_firewall_rules_value1', 'health_check_blocking_firewall_rules_value2']}], 'backend_type': 1, 'backend_uri': 'backend_uri_value'}, 'network': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_subnet_uri': 'matched_subnet_uri_value', 'matched_ip_range': 'matched_ip_range_value', 'region': 'region_value'}, 'gke_master': {'cluster_uri': 'cluster_uri_value', 'cluster_network_uri': 'cluster_network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'dns_endpoint': 'dns_endpoint_value'}, 'cloud_sql_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'region': 'region_value'}, 'redis_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'primary_endpoint_ip': 'primary_endpoint_ip_value', 'read_endpoint_ip': 'read_endpoint_ip_value', 'region': 'region_value'}, 'redis_cluster': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'discovery_endpoint_ip_address': 'discovery_endpoint_ip_address_value', 'secondary_endpoint_ip_address': 'secondary_endpoint_ip_address_value', 'location': 'location_value'}, 'cloud_function': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'version_id': 1074}, 'app_engine_version': {'display_name': 'display_name_value', 'uri': 'uri_value', 'runtime': 'runtime_value', 'environment': 'environment_value'}, 'cloud_run_revision': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'service_uri': 'service_uri_value'}, 'nat': {'type_': 1, 'protocol': 'protocol_value', 'network_uri': 'network_uri_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'router_uri': 'router_uri_value', 'nat_gateway_name': 'nat_gateway_name_value'}, 'proxy_connection': {'protocol': 'protocol_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'subnet_uri': 'subnet_uri_value', 'network_uri': 'network_uri_value'}, 'load_balancer_backend_info': {'name': 'name_value', 'instance_uri': 'instance_uri_value', 'backend_service_uri': 'backend_service_uri_value', 'instance_group_uri': 'instance_group_uri_value', 'network_endpoint_group_uri': 'network_endpoint_group_uri_value', 'backend_bucket_uri': 'backend_bucket_uri_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value', 'health_check_uri': 'health_check_uri_value', 'health_check_firewalls_config_state': 1}, 'storage_bucket': {'bucket': 'bucket_value'}, 'serverless_neg': {'neg_uri': 'neg_uri_value'}}], 'forward_trace_id': 1679}]}, 'probing_details': {'result': 1, 'verify_time': {}, 'error': {}, 'abort_cause': 1, 'sent_probe_count': 1721, 'successful_probe_count': 2367, 'endpoint_info': {}, 'probing_latency': {'latency_percentiles': [{'percent': 753, 'latency_micros': 1500}]}, 'destination_egress_location': {'metropolitan_area': 'metropolitan_area_value'}}, 'bypass_firewall_checks': True} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = reachability.CreateConnectivityTestRequest.meta.fields["resource"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["resource"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["resource"][field])): - del request_init["resource"][field][i][subfield] - else: - del request_init["resource"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_create_connectivity_test") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_create_connectivity_test") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.CreateConnectivityTestRequest.pb(reachability.CreateConnectivityTestRequest()) - 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 = reachability.CreateConnectivityTestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_connectivity_test_rest_bad_request(request_type=reachability.UpdateConnectivityTestRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/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.update_connectivity_test(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.UpdateConnectivityTestRequest, - dict, -]) -def test_update_connectivity_test_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/sample2'}} - request_init["resource"] = {'name': 'projects/sample1/locations/global/connectivityTests/sample2', 'description': 'description_value', 'source': {'ip_address': 'ip_address_value', 'port': 453, 'instance': 'instance_value', 'forwarding_rule': 'forwarding_rule_value', 'forwarding_rule_target': 1, 'load_balancer_id': 'load_balancer_id_value', 'load_balancer_type': 1, 'gke_master_cluster': 'gke_master_cluster_value', 'fqdn': 'fqdn_value', 'cloud_sql_instance': 'cloud_sql_instance_value', 'redis_instance': 'redis_instance_value', 'redis_cluster': 'redis_cluster_value', 'cloud_function': {'uri': 'uri_value'}, 'app_engine_version': {'uri': 'uri_value'}, 'cloud_run_revision': {'uri': 'uri_value'}, 'network': 'network_value', 'network_type': 1, 'project_id': 'project_id_value'}, 'destination': {}, 'protocol': 'protocol_value', 'related_projects': ['related_projects_value1', 'related_projects_value2'], 'display_name': 'display_name_value', 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'reachability_details': {'result': 1, 'verify_time': {}, 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'traces': [{'endpoint_info': {'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'protocol': 'protocol_value', 'source_port': 1205, 'destination_port': 1734, 'source_network_uri': 'source_network_uri_value', 'destination_network_uri': 'destination_network_uri_value', 'source_agent_uri': 'source_agent_uri_value'}, 'steps': [{'description': 'description_value', 'state': 1, 'causes_drop': True, 'project_id': 'project_id_value', 'instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'interface': 'interface_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'network_tags': ['network_tags_value1', 'network_tags_value2'], 'service_account': 'service_account_value', 'psc_network_attachment_uri': 'psc_network_attachment_uri_value'}, 'firewall': {'display_name': 'display_name_value', 'uri': 'uri_value', 'direction': 'direction_value', 'action': 'action_value', 'priority': 898, 'network_uri': 'network_uri_value', 'target_tags': ['target_tags_value1', 'target_tags_value2'], 'target_service_accounts': ['target_service_accounts_value1', 'target_service_accounts_value2'], 'policy': 'policy_value', 'policy_uri': 'policy_uri_value', 'firewall_rule_type': 1}, 'route': {'route_type': 1, 'next_hop_type': 1, 'route_scope': 1, 'display_name': 'display_name_value', 'uri': 'uri_value', 'region': 'region_value', 'dest_ip_range': 'dest_ip_range_value', 'next_hop': 'next_hop_value', 'network_uri': 'network_uri_value', 'priority': 898, 'instance_tags': ['instance_tags_value1', 'instance_tags_value2'], 'src_ip_range': 'src_ip_range_value', 'dest_port_ranges': ['dest_port_ranges_value1', 'dest_port_ranges_value2'], 'src_port_ranges': ['src_port_ranges_value1', 'src_port_ranges_value2'], 'protocols': ['protocols_value1', 'protocols_value2'], 'ncc_hub_uri': 'ncc_hub_uri_value', 'ncc_spoke_uri': 'ncc_spoke_uri_value', 'advertised_route_source_router_uri': 'advertised_route_source_router_uri_value', 'advertised_route_next_hop_uri': 'advertised_route_next_hop_uri_value'}, 'endpoint': {}, 'google_service': {'source_ip': 'source_ip_value', 'google_service_type': 1}, 'forwarding_rule': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_protocol': 'matched_protocol_value', 'matched_port_range': 'matched_port_range_value', 'vip': 'vip_value', 'target': 'target_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'load_balancer_name': 'load_balancer_name_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'vpn_gateway': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'ip_address': 'ip_address_value', 'vpn_tunnel_uri': 'vpn_tunnel_uri_value', 'region': 'region_value'}, 'vpn_tunnel': {'display_name': 'display_name_value', 'uri': 'uri_value', 'source_gateway': 'source_gateway_value', 'remote_gateway': 'remote_gateway_value', 'remote_gateway_ip': 'remote_gateway_ip_value', 'source_gateway_ip': 'source_gateway_ip_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'routing_type': 1}, 'vpc_connector': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value'}, 'deliver': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'storage_bucket': 'storage_bucket_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'forward': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value'}, 'abort': {'cause': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'projects_missing_permission': ['projects_missing_permission_value1', 'projects_missing_permission_value2']}, 'drop': {'cause': 1, 'resource_uri': 'resource_uri_value', 'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'region': 'region_value'}, 'load_balancer': {'load_balancer_type': 1, 'health_check_uri': 'health_check_uri_value', 'backends': [{'display_name': 'display_name_value', 'uri': 'uri_value', 'health_check_firewall_state': 1, 'health_check_allowing_firewall_rules': ['health_check_allowing_firewall_rules_value1', 'health_check_allowing_firewall_rules_value2'], 'health_check_blocking_firewall_rules': ['health_check_blocking_firewall_rules_value1', 'health_check_blocking_firewall_rules_value2']}], 'backend_type': 1, 'backend_uri': 'backend_uri_value'}, 'network': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_subnet_uri': 'matched_subnet_uri_value', 'matched_ip_range': 'matched_ip_range_value', 'region': 'region_value'}, 'gke_master': {'cluster_uri': 'cluster_uri_value', 'cluster_network_uri': 'cluster_network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'dns_endpoint': 'dns_endpoint_value'}, 'cloud_sql_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'region': 'region_value'}, 'redis_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'primary_endpoint_ip': 'primary_endpoint_ip_value', 'read_endpoint_ip': 'read_endpoint_ip_value', 'region': 'region_value'}, 'redis_cluster': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'discovery_endpoint_ip_address': 'discovery_endpoint_ip_address_value', 'secondary_endpoint_ip_address': 'secondary_endpoint_ip_address_value', 'location': 'location_value'}, 'cloud_function': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'version_id': 1074}, 'app_engine_version': {'display_name': 'display_name_value', 'uri': 'uri_value', 'runtime': 'runtime_value', 'environment': 'environment_value'}, 'cloud_run_revision': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'service_uri': 'service_uri_value'}, 'nat': {'type_': 1, 'protocol': 'protocol_value', 'network_uri': 'network_uri_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'router_uri': 'router_uri_value', 'nat_gateway_name': 'nat_gateway_name_value'}, 'proxy_connection': {'protocol': 'protocol_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'subnet_uri': 'subnet_uri_value', 'network_uri': 'network_uri_value'}, 'load_balancer_backend_info': {'name': 'name_value', 'instance_uri': 'instance_uri_value', 'backend_service_uri': 'backend_service_uri_value', 'instance_group_uri': 'instance_group_uri_value', 'network_endpoint_group_uri': 'network_endpoint_group_uri_value', 'backend_bucket_uri': 'backend_bucket_uri_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value', 'health_check_uri': 'health_check_uri_value', 'health_check_firewalls_config_state': 1}, 'storage_bucket': {'bucket': 'bucket_value'}, 'serverless_neg': {'neg_uri': 'neg_uri_value'}}], 'forward_trace_id': 1679}]}, 'probing_details': {'result': 1, 'verify_time': {}, 'error': {}, 'abort_cause': 1, 'sent_probe_count': 1721, 'successful_probe_count': 2367, 'endpoint_info': {}, 'probing_latency': {'latency_percentiles': [{'percent': 753, 'latency_micros': 1500}]}, 'destination_egress_location': {'metropolitan_area': 'metropolitan_area_value'}}, 'bypass_firewall_checks': True} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = reachability.UpdateConnectivityTestRequest.meta.fields["resource"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["resource"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["resource"][field])): - del request_init["resource"][field][i][subfield] - else: - del request_init["resource"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_update_connectivity_test") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_update_connectivity_test") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.UpdateConnectivityTestRequest.pb(reachability.UpdateConnectivityTestRequest()) - 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 = reachability.UpdateConnectivityTestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_rerun_connectivity_test_rest_bad_request(request_type=reachability.RerunConnectivityTestRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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.rerun_connectivity_test(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.RerunConnectivityTestRequest, - dict, -]) -def test_rerun_connectivity_test_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # 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.rerun_connectivity_test(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_rerun_connectivity_test_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_rerun_connectivity_test") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_rerun_connectivity_test") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.RerunConnectivityTestRequest.pb(reachability.RerunConnectivityTestRequest()) - 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 = reachability.RerunConnectivityTestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.rerun_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_connectivity_test_rest_bad_request(request_type=reachability.DeleteConnectivityTestRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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.delete_connectivity_test(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.DeleteConnectivityTestRequest, - dict, -]) -def test_delete_connectivity_test_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_delete_connectivity_test") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_delete_connectivity_test") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.DeleteConnectivityTestRequest.pb(reachability.DeleteConnectivityTestRequest()) - 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 = reachability.DeleteConnectivityTestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_connectivity_test(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 = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - 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_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/global'}, 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/global'} - 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 = ReachabilityServiceClient( - 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_connectivity_tests_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - client.list_connectivity_tests(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.ListConnectivityTestsRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - client.get_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.GetConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__call__') as call: - client.create_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.CreateConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__call__') as call: - client.update_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.UpdateConnectivityTestRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_rerun_connectivity_test_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - client.rerun_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.RerunConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__call__') as call: - client.delete_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.DeleteConnectivityTestRequest() - - assert args[0] == request_msg - - -def test_reachability_service_rest_lro_client(): - client = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ReachabilityServiceGrpcTransport, - ) - -def test_reachability_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ReachabilityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_reachability_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ReachabilityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_connectivity_tests', - 'get_connectivity_test', - 'create_connectivity_test', - 'update_connectivity_test', - 'rerun_connectivity_test', - 'delete_connectivity_test', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_reachability_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ReachabilityServiceTransport( - 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_reachability_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ReachabilityServiceTransport() - adc.assert_called_once() - - -def test_reachability_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ReachabilityServiceClient() - 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.ReachabilityServiceGrpcTransport, - transports.ReachabilityServiceGrpcAsyncIOTransport, - ], -) -def test_reachability_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ReachabilityServiceGrpcTransport, - transports.ReachabilityServiceGrpcAsyncIOTransport, - transports.ReachabilityServiceRestTransport, - ], -) -def test_reachability_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ReachabilityServiceGrpcTransport, grpc_helpers), - (transports.ReachabilityServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_reachability_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "networkmanagement.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="networkmanagement.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) -def test_reachability_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_reachability_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ReachabilityServiceRestTransport ( - 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_reachability_service_host_no_port(transport_name): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networkmanagement.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networkmanagement.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networkmanagement.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_reachability_service_host_with_port(transport_name): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networkmanagement.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networkmanagement.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networkmanagement.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_reachability_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ReachabilityServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ReachabilityServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_connectivity_tests._session - session2 = client2.transport.list_connectivity_tests._session - assert session1 != session2 - session1 = client1.transport.get_connectivity_test._session - session2 = client2.transport.get_connectivity_test._session - assert session1 != session2 - session1 = client1.transport.create_connectivity_test._session - session2 = client2.transport.create_connectivity_test._session - assert session1 != session2 - session1 = client1.transport.update_connectivity_test._session - session2 = client2.transport.update_connectivity_test._session - assert session1 != session2 - session1 = client1.transport.rerun_connectivity_test._session - session2 = client2.transport.rerun_connectivity_test._session - assert session1 != session2 - session1 = client1.transport.delete_connectivity_test._session - session2 = client2.transport.delete_connectivity_test._session - assert session1 != session2 -def test_reachability_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ReachabilityServiceGrpcTransport( - 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_reachability_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ReachabilityServiceGrpcAsyncIOTransport( - 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.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) -def test_reachability_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) -def test_reachability_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_reachability_service_grpc_lro_client(): - client = ReachabilityServiceClient( - 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_reachability_service_grpc_lro_async_client(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test_path(): - project = "squid" - test = "clam" - expected = "projects/{project}/locations/global/connectivityTests/{test}".format(project=project, test=test, ) - actual = ReachabilityServiceClient.connectivity_test_path(project, test) - assert expected == actual - - -def test_parse_connectivity_test_path(): - expected = { - "project": "whelk", - "test": "octopus", - } - path = ReachabilityServiceClient.connectivity_test_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.parse_connectivity_test_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ReachabilityServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = ReachabilityServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = ReachabilityServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = ReachabilityServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ReachabilityServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = ReachabilityServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = ReachabilityServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = ReachabilityServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ReachabilityServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = ReachabilityServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.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.ReachabilityServiceTransport, '_prep_wrapped_messages') as prep: - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ReachabilityServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ReachabilityServiceClient.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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - 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", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py b/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py index 785067d93b3c..558c8aab67c5 100644 --- a/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py +++ b/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.21.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py b/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py index 785067d93b3c..558c8aab67c5 100644 --- a/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py +++ b/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.21.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json b/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json index 3d2d6615bfef..a6a39ec02f7f 100644 --- a/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json +++ b/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-management", - "version": "1.21.0" + "version": "0.1.0" }, "snippets": [ { From a3cd3022f8cea38237a0488f2ccfd3b9229e93c8 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 14 Nov 2024 09:05:00 +0000 Subject: [PATCH 3/4] feat: add round-trip mode PiperOrigin-RevId: 696396549 Source-Link: https://github.com/googleapis/googleapis/commit/2d08f07eab9bbe8300cd20b871d0811bbb693fab Source-Link: https://github.com/googleapis/googleapis-gen/commit/4338ccad05c7f87b6747a12b32a3a3f96b81b81e Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLW5ldHdvcmstbWFuYWdlbWVudC8uT3dsQm90LnlhbWwiLCJoIjoiNDMzOGNjYWQwNWM3Zjg3YjY3NDdhMTJiMzJhM2EzZjk2YjgxYjgxZSJ9 --- .../v1/.coveragerc | 13 + .../v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../reachability_service.rst | 10 + .../docs/network_management_v1/services_.rst | 6 + .../v1/docs/network_management_v1/types_.rst | 6 + .../cloud/network_management/__init__.py | 117 + .../cloud/network_management/gapic_version.py | 16 + .../google/cloud/network_management/py.typed | 2 + .../cloud/network_management_v1/__init__.py | 118 + .../network_management_v1/gapic_metadata.json | 118 + .../network_management_v1/gapic_version.py | 16 + .../cloud/network_management_v1/py.typed | 2 + .../services/__init__.py | 15 + .../services/reachability_service/__init__.py | 22 + .../reachability_service/async_client.py | 1597 ++++ .../services/reachability_service/client.py | 1917 +++++ .../services/reachability_service/pagers.py | 163 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../reachability_service/transports/base.py | 362 + .../reachability_service/transports/grpc.py | 660 ++ .../transports/grpc_asyncio.py | 751 ++ .../reachability_service/transports/rest.py | 1714 ++++ .../transports/rest_base.py | 588 ++ .../network_management_v1/types/__init__.py | 114 + .../types/connectivity_test.py | 753 ++ .../types/reachability.py | 293 + .../network_management_v1/types/trace.py | 3164 +++++++ .../v1/mypy.ini | 3 + .../v1/noxfile.py | 280 + ..._service_create_connectivity_test_async.py | 57 + ...y_service_create_connectivity_test_sync.py | 57 + ..._service_delete_connectivity_test_async.py | 56 + ...y_service_delete_connectivity_test_sync.py | 56 + ...ity_service_get_connectivity_test_async.py | 52 + ...lity_service_get_connectivity_test_sync.py | 52 + ...y_service_list_connectivity_tests_async.py | 53 + ...ty_service_list_connectivity_tests_sync.py | 53 + ...y_service_rerun_connectivity_test_async.py | 56 + ...ty_service_rerun_connectivity_test_sync.py | 56 + ..._service_update_connectivity_test_async.py | 55 + ...y_service_update_connectivity_test_sync.py | 55 + ...ata_google.cloud.networkmanagement.v1.json | 997 +++ .../fixup_network_management_v1_keywords.py | 181 + .../v1/setup.py | 99 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.13.txt | 7 + .../v1/testing/constraints-3.7.txt | 11 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/network_management_v1/__init__.py | 16 + .../test_reachability_service.py | 7469 +++++++++++++++++ 62 files changed, 22858 insertions(+) create mode 100644 owl-bot-staging/google-cloud-network-management/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-network-management/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-network-management/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-network-management/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json create mode 100644 owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/.coveragerc b/owl-bot-staging/google-cloud-network-management/v1/.coveragerc new file mode 100644 index 000000000000..20f78aac3034 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/network_management/__init__.py + google/cloud/network_management/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-network-management/v1/.flake8 b/owl-bot-staging/google-cloud-network-management/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in b/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in new file mode 100644 index 000000000000..240002b7c5c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/network_management *.py +recursive-include google/cloud/network_management_v1 *.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/README.rst b/owl-bot-staging/google-cloud-network-management/v1/README.rst new file mode 100644 index 000000000000..264724cca11b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Network Management 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 Network Management 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-network-management/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py b/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py new file mode 100644 index 000000000000..a303b54b23a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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-network-management documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-network-management" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-network-management-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-network-management.tex", + u"google-cloud-network-management Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-network-management", + u"Google Cloud Network Management 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-network-management", + u"google-cloud-network-management Documentation", + author, + "google-cloud-network-management", + "GAPIC library for Google Cloud Network Management 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-network-management/v1/docs/index.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/index.rst new file mode 100644 index 000000000000..df608d7805a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + network_management_v1/services_ + network_management_v1/types_ diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst new file mode 100644 index 000000000000..1d3502a632c9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst @@ -0,0 +1,10 @@ +ReachabilityService +------------------------------------- + +.. automodule:: google.cloud.network_management_v1.services.reachability_service + :members: + :inherited-members: + +.. automodule:: google.cloud.network_management_v1.services.reachability_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst new file mode 100644 index 000000000000..e26ca50e5fc4 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Network Management v1 API +=================================================== +.. toctree:: + :maxdepth: 2 + + reachability_service diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst new file mode 100644 index 000000000000..11bcca7b4b58 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Network Management v1 API +================================================ + +.. automodule:: google.cloud.network_management_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py new file mode 100644 index 000000000000..23a237dd11fa --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py @@ -0,0 +1,117 @@ +# -*- 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.network_management import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.network_management_v1.services.reachability_service.client import ReachabilityServiceClient +from google.cloud.network_management_v1.services.reachability_service.async_client import ReachabilityServiceAsyncClient + +from google.cloud.network_management_v1.types.connectivity_test import ConnectivityTest +from google.cloud.network_management_v1.types.connectivity_test import Endpoint +from google.cloud.network_management_v1.types.connectivity_test import LatencyDistribution +from google.cloud.network_management_v1.types.connectivity_test import LatencyPercentile +from google.cloud.network_management_v1.types.connectivity_test import ProbingDetails +from google.cloud.network_management_v1.types.connectivity_test import ReachabilityDetails +from google.cloud.network_management_v1.types.reachability import CreateConnectivityTestRequest +from google.cloud.network_management_v1.types.reachability import DeleteConnectivityTestRequest +from google.cloud.network_management_v1.types.reachability import GetConnectivityTestRequest +from google.cloud.network_management_v1.types.reachability import ListConnectivityTestsRequest +from google.cloud.network_management_v1.types.reachability import ListConnectivityTestsResponse +from google.cloud.network_management_v1.types.reachability import OperationMetadata +from google.cloud.network_management_v1.types.reachability import RerunConnectivityTestRequest +from google.cloud.network_management_v1.types.reachability import UpdateConnectivityTestRequest +from google.cloud.network_management_v1.types.trace import AbortInfo +from google.cloud.network_management_v1.types.trace import AppEngineVersionInfo +from google.cloud.network_management_v1.types.trace import CloudFunctionInfo +from google.cloud.network_management_v1.types.trace import CloudRunRevisionInfo +from google.cloud.network_management_v1.types.trace import CloudSQLInstanceInfo +from google.cloud.network_management_v1.types.trace import DeliverInfo +from google.cloud.network_management_v1.types.trace import DropInfo +from google.cloud.network_management_v1.types.trace import EndpointInfo +from google.cloud.network_management_v1.types.trace import FirewallInfo +from google.cloud.network_management_v1.types.trace import ForwardInfo +from google.cloud.network_management_v1.types.trace import ForwardingRuleInfo +from google.cloud.network_management_v1.types.trace import GKEMasterInfo +from google.cloud.network_management_v1.types.trace import GoogleServiceInfo +from google.cloud.network_management_v1.types.trace import InstanceInfo +from google.cloud.network_management_v1.types.trace import LoadBalancerBackend +from google.cloud.network_management_v1.types.trace import LoadBalancerBackendInfo +from google.cloud.network_management_v1.types.trace import LoadBalancerInfo +from google.cloud.network_management_v1.types.trace import NatInfo +from google.cloud.network_management_v1.types.trace import NetworkInfo +from google.cloud.network_management_v1.types.trace import ProxyConnectionInfo +from google.cloud.network_management_v1.types.trace import RedisClusterInfo +from google.cloud.network_management_v1.types.trace import RedisInstanceInfo +from google.cloud.network_management_v1.types.trace import RouteInfo +from google.cloud.network_management_v1.types.trace import ServerlessNegInfo +from google.cloud.network_management_v1.types.trace import Step +from google.cloud.network_management_v1.types.trace import StorageBucketInfo +from google.cloud.network_management_v1.types.trace import Trace +from google.cloud.network_management_v1.types.trace import VpcConnectorInfo +from google.cloud.network_management_v1.types.trace import VpnGatewayInfo +from google.cloud.network_management_v1.types.trace import VpnTunnelInfo +from google.cloud.network_management_v1.types.trace import LoadBalancerType + +__all__ = ('ReachabilityServiceClient', + 'ReachabilityServiceAsyncClient', + 'ConnectivityTest', + 'Endpoint', + 'LatencyDistribution', + 'LatencyPercentile', + 'ProbingDetails', + 'ReachabilityDetails', + 'CreateConnectivityTestRequest', + 'DeleteConnectivityTestRequest', + 'GetConnectivityTestRequest', + 'ListConnectivityTestsRequest', + 'ListConnectivityTestsResponse', + 'OperationMetadata', + 'RerunConnectivityTestRequest', + 'UpdateConnectivityTestRequest', + 'AbortInfo', + 'AppEngineVersionInfo', + 'CloudFunctionInfo', + 'CloudRunRevisionInfo', + 'CloudSQLInstanceInfo', + 'DeliverInfo', + 'DropInfo', + 'EndpointInfo', + 'FirewallInfo', + 'ForwardInfo', + 'ForwardingRuleInfo', + 'GKEMasterInfo', + 'GoogleServiceInfo', + 'InstanceInfo', + 'LoadBalancerBackend', + 'LoadBalancerBackendInfo', + 'LoadBalancerInfo', + 'NatInfo', + 'NetworkInfo', + 'ProxyConnectionInfo', + 'RedisClusterInfo', + 'RedisInstanceInfo', + 'RouteInfo', + 'ServerlessNegInfo', + 'Step', + 'StorageBucketInfo', + 'Trace', + 'VpcConnectorInfo', + 'VpnGatewayInfo', + 'VpnTunnelInfo', + 'LoadBalancerType', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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-network-management/v1/google/cloud/network_management/py.typed b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed new file mode 100644 index 000000000000..5aa063ef7ba9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-management package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py new file mode 100644 index 000000000000..a55edfec563a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py @@ -0,0 +1,118 @@ +# -*- 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.network_management_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.reachability_service import ReachabilityServiceClient +from .services.reachability_service import ReachabilityServiceAsyncClient + +from .types.connectivity_test import ConnectivityTest +from .types.connectivity_test import Endpoint +from .types.connectivity_test import LatencyDistribution +from .types.connectivity_test import LatencyPercentile +from .types.connectivity_test import ProbingDetails +from .types.connectivity_test import ReachabilityDetails +from .types.reachability import CreateConnectivityTestRequest +from .types.reachability import DeleteConnectivityTestRequest +from .types.reachability import GetConnectivityTestRequest +from .types.reachability import ListConnectivityTestsRequest +from .types.reachability import ListConnectivityTestsResponse +from .types.reachability import OperationMetadata +from .types.reachability import RerunConnectivityTestRequest +from .types.reachability import UpdateConnectivityTestRequest +from .types.trace import AbortInfo +from .types.trace import AppEngineVersionInfo +from .types.trace import CloudFunctionInfo +from .types.trace import CloudRunRevisionInfo +from .types.trace import CloudSQLInstanceInfo +from .types.trace import DeliverInfo +from .types.trace import DropInfo +from .types.trace import EndpointInfo +from .types.trace import FirewallInfo +from .types.trace import ForwardInfo +from .types.trace import ForwardingRuleInfo +from .types.trace import GKEMasterInfo +from .types.trace import GoogleServiceInfo +from .types.trace import InstanceInfo +from .types.trace import LoadBalancerBackend +from .types.trace import LoadBalancerBackendInfo +from .types.trace import LoadBalancerInfo +from .types.trace import NatInfo +from .types.trace import NetworkInfo +from .types.trace import ProxyConnectionInfo +from .types.trace import RedisClusterInfo +from .types.trace import RedisInstanceInfo +from .types.trace import RouteInfo +from .types.trace import ServerlessNegInfo +from .types.trace import Step +from .types.trace import StorageBucketInfo +from .types.trace import Trace +from .types.trace import VpcConnectorInfo +from .types.trace import VpnGatewayInfo +from .types.trace import VpnTunnelInfo +from .types.trace import LoadBalancerType + +__all__ = ( + 'ReachabilityServiceAsyncClient', +'AbortInfo', +'AppEngineVersionInfo', +'CloudFunctionInfo', +'CloudRunRevisionInfo', +'CloudSQLInstanceInfo', +'ConnectivityTest', +'CreateConnectivityTestRequest', +'DeleteConnectivityTestRequest', +'DeliverInfo', +'DropInfo', +'Endpoint', +'EndpointInfo', +'FirewallInfo', +'ForwardInfo', +'ForwardingRuleInfo', +'GKEMasterInfo', +'GetConnectivityTestRequest', +'GoogleServiceInfo', +'InstanceInfo', +'LatencyDistribution', +'LatencyPercentile', +'ListConnectivityTestsRequest', +'ListConnectivityTestsResponse', +'LoadBalancerBackend', +'LoadBalancerBackendInfo', +'LoadBalancerInfo', +'LoadBalancerType', +'NatInfo', +'NetworkInfo', +'OperationMetadata', +'ProbingDetails', +'ProxyConnectionInfo', +'ReachabilityDetails', +'ReachabilityServiceClient', +'RedisClusterInfo', +'RedisInstanceInfo', +'RerunConnectivityTestRequest', +'RouteInfo', +'ServerlessNegInfo', +'Step', +'StorageBucketInfo', +'Trace', +'UpdateConnectivityTestRequest', +'VpcConnectorInfo', +'VpnGatewayInfo', +'VpnTunnelInfo', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json new file mode 100644 index 000000000000..6c5315440fef --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json @@ -0,0 +1,118 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.network_management_v1", + "protoPackage": "google.cloud.networkmanagement.v1", + "schema": "1.0", + "services": { + "ReachabilityService": { + "clients": { + "grpc": { + "libraryClient": "ReachabilityServiceClient", + "rpcs": { + "CreateConnectivityTest": { + "methods": [ + "create_connectivity_test" + ] + }, + "DeleteConnectivityTest": { + "methods": [ + "delete_connectivity_test" + ] + }, + "GetConnectivityTest": { + "methods": [ + "get_connectivity_test" + ] + }, + "ListConnectivityTests": { + "methods": [ + "list_connectivity_tests" + ] + }, + "RerunConnectivityTest": { + "methods": [ + "rerun_connectivity_test" + ] + }, + "UpdateConnectivityTest": { + "methods": [ + "update_connectivity_test" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ReachabilityServiceAsyncClient", + "rpcs": { + "CreateConnectivityTest": { + "methods": [ + "create_connectivity_test" + ] + }, + "DeleteConnectivityTest": { + "methods": [ + "delete_connectivity_test" + ] + }, + "GetConnectivityTest": { + "methods": [ + "get_connectivity_test" + ] + }, + "ListConnectivityTests": { + "methods": [ + "list_connectivity_tests" + ] + }, + "RerunConnectivityTest": { + "methods": [ + "rerun_connectivity_test" + ] + }, + "UpdateConnectivityTest": { + "methods": [ + "update_connectivity_test" + ] + } + } + }, + "rest": { + "libraryClient": "ReachabilityServiceClient", + "rpcs": { + "CreateConnectivityTest": { + "methods": [ + "create_connectivity_test" + ] + }, + "DeleteConnectivityTest": { + "methods": [ + "delete_connectivity_test" + ] + }, + "GetConnectivityTest": { + "methods": [ + "get_connectivity_test" + ] + }, + "ListConnectivityTests": { + "methods": [ + "list_connectivity_tests" + ] + }, + "RerunConnectivityTest": { + "methods": [ + "rerun_connectivity_test" + ] + }, + "UpdateConnectivityTest": { + "methods": [ + "update_connectivity_test" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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-network-management/v1/google/cloud/network_management_v1/py.typed b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed new file mode 100644 index 000000000000..5aa063ef7ba9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-management package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py new file mode 100644 index 000000000000..6f536eeb4ca5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 ReachabilityServiceClient +from .async_client import ReachabilityServiceAsyncClient + +__all__ = ( + 'ReachabilityServiceClient', + 'ReachabilityServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py new file mode 100644 index 000000000000..0ae89e6c03d8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py @@ -0,0 +1,1597 @@ +# -*- 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.network_management_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.location import locations_pb2 # type: ignore +from google.cloud.network_management_v1.services.reachability_service import pagers +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport +from .client import ReachabilityServiceClient + + +class ReachabilityServiceAsyncClient: + """The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + """ + + _client: ReachabilityServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ReachabilityServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ReachabilityServiceClient._DEFAULT_UNIVERSE + + connectivity_test_path = staticmethod(ReachabilityServiceClient.connectivity_test_path) + parse_connectivity_test_path = staticmethod(ReachabilityServiceClient.parse_connectivity_test_path) + common_billing_account_path = staticmethod(ReachabilityServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ReachabilityServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ReachabilityServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ReachabilityServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ReachabilityServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ReachabilityServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ReachabilityServiceClient.common_project_path) + parse_common_project_path = staticmethod(ReachabilityServiceClient.parse_common_project_path) + common_location_path = staticmethod(ReachabilityServiceClient.common_location_path) + parse_common_location_path = staticmethod(ReachabilityServiceClient.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: + ReachabilityServiceAsyncClient: The constructed client. + """ + return ReachabilityServiceClient.from_service_account_info.__func__(ReachabilityServiceAsyncClient, 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: + ReachabilityServiceAsyncClient: The constructed client. + """ + return ReachabilityServiceClient.from_service_account_file.__func__(ReachabilityServiceAsyncClient, 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 ReachabilityServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ReachabilityServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ReachabilityServiceTransport: 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 = ReachabilityServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ReachabilityServiceTransport, Callable[..., ReachabilityServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the reachability service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ReachabilityServiceTransport,Callable[..., ReachabilityServiceTransport]]]): + 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 ReachabilityServiceTransport 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 = ReachabilityServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_connectivity_tests(self, + request: Optional[Union[reachability.ListConnectivityTestsRequest, 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.ListConnectivityTestsAsyncPager: + r"""Lists all Connectivity Tests owned by a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_list_connectivity_tests(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.ListConnectivityTestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_connectivity_tests(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.ListConnectivityTestsRequest, dict]]): + The request object. Request for the ``ListConnectivityTests`` method. + parent (:class:`str`): + Required. The parent resource of the Connectivity Tests: + ``projects/{project_id}/locations/global`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsAsyncPager: + Response for the ListConnectivityTests method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, reachability.ListConnectivityTestsRequest): + request = reachability.ListConnectivityTestsRequest(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_connectivity_tests] + + # 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.ListConnectivityTestsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_connectivity_test(self, + request: Optional[Union[reachability.GetConnectivityTestRequest, 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]] = (), + ) -> connectivity_test.ConnectivityTest: + r"""Gets the details of a specific Connectivity Test. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_get_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.GetConnectivityTestRequest( + name="name_value", + ) + + # Make the request + response = await client.get_connectivity_test(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.GetConnectivityTestRequest, dict]]): + The request object. Request for the ``GetConnectivityTest`` method. + name (:class:`str`): + Required. ``ConnectivityTest`` resource name using the + form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + + 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.network_management_v1.types.ConnectivityTest: + A Connectivity Test for a network + reachability analysis. + + """ + # Create or coerce a 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, reachability.GetConnectivityTestRequest): + request = reachability.GetConnectivityTestRequest(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_connectivity_test] + + # 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_connectivity_test(self, + request: Optional[Union[reachability.CreateConnectivityTestRequest, dict]] = None, + *, + parent: Optional[str] = None, + test_id: Optional[str] = None, + resource: Optional[connectivity_test.ConnectivityTest] = 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 Connectivity Test. After you create a test, the + reachability analysis is performed as part of the long running + operation, which completes when the analysis completes. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, containing non-existent resources in the + network, or you don't have read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + AMBIGUOUS. For more information, see the Connectivity Test + documentation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_create_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.CreateConnectivityTestRequest( + parent="parent_value", + test_id="test_id_value", + ) + + # Make the request + operation = client.create_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.CreateConnectivityTestRequest, dict]]): + The request object. Request for the ``CreateConnectivityTest`` method. + parent (:class:`str`): + Required. The parent resource of the Connectivity Test + to create: ``projects/{project_id}/locations/global`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_id (:class:`str`): + Required. The logical name of the Connectivity Test in + your project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-40 characters. + - Must end with a number or a letter. + - Must be unique within the customer project + + This corresponds to the ``test_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (:class:`google.cloud.network_management_v1.types.ConnectivityTest`): + Required. A ``ConnectivityTest`` resource + This corresponds to the ``resource`` 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.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a 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, test_id, resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.CreateConnectivityTestRequest): + request = reachability.CreateConnectivityTestRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if test_id is not None: + request.test_id = test_id + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_connectivity_test] + + # 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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_connectivity_test(self, + request: Optional[Union[reachability.UpdateConnectivityTestRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + resource: Optional[connectivity_test.ConnectivityTest] = 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 configuration of an existing ``ConnectivityTest``. + After you update a test, the reachability analysis is performed + as part of the long running operation, which completes when the + analysis completes. The Reachability state in the test resource + is updated with the new result. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, they contain non-existent resources in the + network, or the user does not have read permissions to the + network configurations of listed projects), then the + reachability result returns a value of UNKNOWN. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for + more details. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_update_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.UpdateConnectivityTestRequest( + ) + + # Make the request + operation = client.update_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.UpdateConnectivityTestRequest, dict]]): + The request object. Request for the ``UpdateConnectivityTest`` method. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask of fields to update. + At least one path must be supplied in + this field. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (:class:`google.cloud.network_management_v1.types.ConnectivityTest`): + Required. Only fields specified in update_mask are + updated. + + This corresponds to the ``resource`` 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.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a 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([update_mask, resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.UpdateConnectivityTestRequest): + request = reachability.UpdateConnectivityTestRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if update_mask is not None: + request.update_mask = update_mask + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_connectivity_test] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource.name", request.resource.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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + async def rerun_connectivity_test(self, + request: Optional[Union[reachability.RerunConnectivityTestRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Rerun an existing ``ConnectivityTest``. After the user triggers + the rerun, the reachability analysis is performed as part of the + long running operation, which completes when the analysis + completes. + + Even though the test configuration remains the same, the + reachability result may change due to underlying network + configuration changes. + + If the endpoint specifications in ``ConnectivityTest`` become + invalid (for example, specified resources are deleted in the + network, or you lost read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_rerun_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.RerunConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.rerun_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.RerunConnectivityTestRequest, dict]]): + The request object. Request for the ``RerunConnectivityTest`` 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: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.RerunConnectivityTestRequest): + request = reachability.RerunConnectivityTestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.rerun_connectivity_test] + + # 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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_connectivity_test(self, + request: Optional[Union[reachability.DeleteConnectivityTestRequest, 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 specific ``ConnectivityTest``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + async def sample_delete_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.DeleteConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_management_v1.types.DeleteConnectivityTestRequest, dict]]): + The request object. Request for the ``DeleteConnectivityTest`` method. + name (:class:`str`): + Required. Connectivity Test resource name using the + form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + + 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, reachability.DeleteConnectivityTestRequest): + request = reachability.DeleteConnectivityTestRequest(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_connectivity_test] + + # 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=reachability.OperationMetadata, + ) + + # 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, 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) -> "ReachabilityServiceAsyncClient": + 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__ = ( + "ReachabilityServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py new file mode 100644 index 000000000000..af1f94e73757 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py @@ -0,0 +1,1917 @@ +# -*- 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.network_management_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.location import locations_pb2 # type: ignore +from google.cloud.network_management_v1.services.reachability_service import pagers +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ReachabilityServiceGrpcTransport +from .transports.grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport +from .transports.rest import ReachabilityServiceRestTransport + + +class ReachabilityServiceClientMeta(type): + """Metaclass for the ReachabilityService 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[ReachabilityServiceTransport]] + _transport_registry["grpc"] = ReachabilityServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ReachabilityServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ReachabilityServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ReachabilityServiceTransport]: + """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 ReachabilityServiceClient(metaclass=ReachabilityServiceClientMeta): + """The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + """ + + @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 = "networkmanagement.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networkmanagement.{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: + ReachabilityServiceClient: 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: + ReachabilityServiceClient: 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) -> ReachabilityServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ReachabilityServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def connectivity_test_path(project: str,test: str,) -> str: + """Returns a fully-qualified connectivity_test string.""" + return "projects/{project}/locations/global/connectivityTests/{test}".format(project=project, test=test, ) + + @staticmethod + def parse_connectivity_test_path(path: str) -> Dict[str,str]: + """Parses a connectivity_test path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/global/connectivityTests/(?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 = ReachabilityServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ReachabilityServiceClient._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 = ReachabilityServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ReachabilityServiceTransport, Callable[..., ReachabilityServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the reachability service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ReachabilityServiceTransport,Callable[..., ReachabilityServiceTransport]]]): + 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 ReachabilityServiceTransport 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 = ReachabilityServiceClient._read_environment_variables() + self._client_cert_source = ReachabilityServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ReachabilityServiceClient._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, ReachabilityServiceTransport) + if transport_provided: + # transport is a ReachabilityServiceTransport 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(ReachabilityServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ReachabilityServiceClient._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[ReachabilityServiceTransport], Callable[..., ReachabilityServiceTransport]] = ( + ReachabilityServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ReachabilityServiceTransport], 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_connectivity_tests(self, + request: Optional[Union[reachability.ListConnectivityTestsRequest, 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.ListConnectivityTestsPager: + r"""Lists all Connectivity Tests owned by a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_list_connectivity_tests(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.ListConnectivityTestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_connectivity_tests(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.ListConnectivityTestsRequest, dict]): + The request object. Request for the ``ListConnectivityTests`` method. + parent (str): + Required. The parent resource of the Connectivity Tests: + ``projects/{project_id}/locations/global`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsPager: + Response for the ListConnectivityTests method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, reachability.ListConnectivityTestsRequest): + request = reachability.ListConnectivityTestsRequest(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_connectivity_tests] + + # 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.ListConnectivityTestsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_connectivity_test(self, + request: Optional[Union[reachability.GetConnectivityTestRequest, 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]] = (), + ) -> connectivity_test.ConnectivityTest: + r"""Gets the details of a specific Connectivity Test. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_get_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.GetConnectivityTestRequest( + name="name_value", + ) + + # Make the request + response = client.get_connectivity_test(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.GetConnectivityTestRequest, dict]): + The request object. Request for the ``GetConnectivityTest`` method. + name (str): + Required. ``ConnectivityTest`` resource name using the + form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + + 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.network_management_v1.types.ConnectivityTest: + A Connectivity Test for a network + reachability analysis. + + """ + # Create or coerce a 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, reachability.GetConnectivityTestRequest): + request = reachability.GetConnectivityTestRequest(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_connectivity_test] + + # 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_connectivity_test(self, + request: Optional[Union[reachability.CreateConnectivityTestRequest, dict]] = None, + *, + parent: Optional[str] = None, + test_id: Optional[str] = None, + resource: Optional[connectivity_test.ConnectivityTest] = 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 Connectivity Test. After you create a test, the + reachability analysis is performed as part of the long running + operation, which completes when the analysis completes. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, containing non-existent resources in the + network, or you don't have read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + AMBIGUOUS. For more information, see the Connectivity Test + documentation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_create_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.CreateConnectivityTestRequest( + parent="parent_value", + test_id="test_id_value", + ) + + # Make the request + operation = client.create_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.CreateConnectivityTestRequest, dict]): + The request object. Request for the ``CreateConnectivityTest`` method. + parent (str): + Required. The parent resource of the Connectivity Test + to create: ``projects/{project_id}/locations/global`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_id (str): + Required. The logical name of the Connectivity Test in + your project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-40 characters. + - Must end with a number or a letter. + - Must be unique within the customer project + + This corresponds to the ``test_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (google.cloud.network_management_v1.types.ConnectivityTest): + Required. A ``ConnectivityTest`` resource + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a 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, test_id, resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.CreateConnectivityTestRequest): + request = reachability.CreateConnectivityTestRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if test_id is not None: + request.test_id = test_id + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_connectivity_test] + + # 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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_connectivity_test(self, + request: Optional[Union[reachability.UpdateConnectivityTestRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + resource: Optional[connectivity_test.ConnectivityTest] = 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 configuration of an existing ``ConnectivityTest``. + After you update a test, the reachability analysis is performed + as part of the long running operation, which completes when the + analysis completes. The Reachability state in the test resource + is updated with the new result. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, they contain non-existent resources in the + network, or the user does not have read permissions to the + network configurations of listed projects), then the + reachability result returns a value of UNKNOWN. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for + more details. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_update_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.UpdateConnectivityTestRequest( + ) + + # Make the request + operation = client.update_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.UpdateConnectivityTestRequest, dict]): + The request object. Request for the ``UpdateConnectivityTest`` method. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. + At least one path must be supplied in + this field. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (google.cloud.network_management_v1.types.ConnectivityTest): + Required. Only fields specified in update_mask are + updated. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a 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([update_mask, resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.UpdateConnectivityTestRequest): + request = reachability.UpdateConnectivityTestRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if update_mask is not None: + request.update_mask = update_mask + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_connectivity_test] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource.name", request.resource.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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + def rerun_connectivity_test(self, + request: Optional[Union[reachability.RerunConnectivityTestRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Rerun an existing ``ConnectivityTest``. After the user triggers + the rerun, the reachability analysis is performed as part of the + long running operation, which completes when the analysis + completes. + + Even though the test configuration remains the same, the + reachability result may change due to underlying network + configuration changes. + + If the endpoint specifications in ``ConnectivityTest`` become + invalid (for example, specified resources are deleted in the + network, or you lost read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_rerun_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.RerunConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.rerun_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.RerunConnectivityTestRequest, dict]): + The request object. Request for the ``RerunConnectivityTest`` 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: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_management_v1.types.ConnectivityTest` + A Connectivity Test for a network reachability analysis. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reachability.RerunConnectivityTestRequest): + request = reachability.RerunConnectivityTestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rerun_connectivity_test] + + # 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, + connectivity_test.ConnectivityTest, + metadata_type=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_connectivity_test(self, + request: Optional[Union[reachability.DeleteConnectivityTestRequest, 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 specific ``ConnectivityTest``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_management_v1 + + def sample_delete_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.DeleteConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_management_v1.types.DeleteConnectivityTestRequest, dict]): + The request object. Request for the ``DeleteConnectivityTest`` method. + name (str): + Required. Connectivity Test resource name using the + form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + + 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, reachability.DeleteConnectivityTestRequest): + request = reachability.DeleteConnectivityTestRequest(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_connectivity_test] + + # 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=reachability.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ReachabilityServiceClient": + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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__ = ( + "ReachabilityServiceClient", +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py new file mode 100644 index 000000000000..99e5a56eabf4 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py @@ -0,0 +1,163 @@ +# -*- 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.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability + + +class ListConnectivityTestsPager: + """A pager for iterating through ``list_connectivity_tests`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConnectivityTests`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` + 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[..., reachability.ListConnectivityTestsResponse], + request: reachability.ListConnectivityTestsRequest, + response: reachability.ListConnectivityTestsResponse, + *, + 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.network_management_v1.types.ListConnectivityTestsRequest): + The initial request object. + response (google.cloud.network_management_v1.types.ListConnectivityTestsResponse): + 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 = reachability.ListConnectivityTestsRequest(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[reachability.ListConnectivityTestsResponse]: + 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[connectivity_test.ConnectivityTest]: + for page in self.pages: + yield from page.resources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConnectivityTestsAsyncPager: + """A pager for iterating through ``list_connectivity_tests`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConnectivityTests`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` + 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[reachability.ListConnectivityTestsResponse]], + request: reachability.ListConnectivityTestsRequest, + response: reachability.ListConnectivityTestsResponse, + *, + 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.network_management_v1.types.ListConnectivityTestsRequest): + The initial request object. + response (google.cloud.network_management_v1.types.ListConnectivityTestsResponse): + 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 = reachability.ListConnectivityTestsRequest(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[reachability.ListConnectivityTestsResponse]: + 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[connectivity_test.ConnectivityTest]: + async def async_generator(): + async for page in self.pages: + for response in page.resources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst new file mode 100644 index 000000000000..b6e73840492e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ReachabilityServiceTransport` is the ABC for all transports. +- public child `ReachabilityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ReachabilityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseReachabilityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ReachabilityServiceRestTransport` 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-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py new file mode 100644 index 000000000000..e03fcb9eb663 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- 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 ReachabilityServiceTransport +from .grpc import ReachabilityServiceGrpcTransport +from .grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport +from .rest import ReachabilityServiceRestTransport +from .rest import ReachabilityServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ReachabilityServiceTransport]] +_transport_registry['grpc'] = ReachabilityServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ReachabilityServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ReachabilityServiceRestTransport + +__all__ = ( + 'ReachabilityServiceTransport', + 'ReachabilityServiceGrpcTransport', + 'ReachabilityServiceGrpcAsyncIOTransport', + 'ReachabilityServiceRestTransport', + 'ReachabilityServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py new file mode 100644 index 000000000000..3d64ec294ab6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py @@ -0,0 +1,362 @@ +# -*- 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.network_management_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.location import locations_pb2 # type: ignore +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ReachabilityServiceTransport(abc.ABC): + """Abstract transport class for ReachabilityService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'networkmanagement.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: 'networkmanagement.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_connectivity_tests: gapic_v1.method.wrap_method( + self.list_connectivity_tests, + default_timeout=None, + client_info=client_info, + ), + self.get_connectivity_test: gapic_v1.method.wrap_method( + self.get_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.create_connectivity_test: gapic_v1.method.wrap_method( + self.create_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.update_connectivity_test: gapic_v1.method.wrap_method( + self.update_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.rerun_connectivity_test: gapic_v1.method.wrap_method( + self.rerun_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.delete_connectivity_test: gapic_v1.method.wrap_method( + self.delete_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_connectivity_tests(self) -> Callable[ + [reachability.ListConnectivityTestsRequest], + Union[ + reachability.ListConnectivityTestsResponse, + Awaitable[reachability.ListConnectivityTestsResponse] + ]]: + raise NotImplementedError() + + @property + def get_connectivity_test(self) -> Callable[ + [reachability.GetConnectivityTestRequest], + Union[ + connectivity_test.ConnectivityTest, + Awaitable[connectivity_test.ConnectivityTest] + ]]: + raise NotImplementedError() + + @property + def create_connectivity_test(self) -> Callable[ + [reachability.CreateConnectivityTestRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_connectivity_test(self) -> Callable[ + [reachability.UpdateConnectivityTestRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rerun_connectivity_test(self) -> Callable[ + [reachability.RerunConnectivityTestRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_connectivity_test(self) -> Callable[ + [reachability.DeleteConnectivityTestRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ReachabilityServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py new file mode 100644 index 000000000000..04909d6e22c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py @@ -0,0 +1,660 @@ +# -*- 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.location import locations_pb2 # type: ignore +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO + + +class ReachabilityServiceGrpcTransport(ReachabilityServiceTransport): + """gRPC backend transport for ReachabilityService. + + The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + + 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 = 'networkmanagement.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: 'networkmanagement.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 = 'networkmanagement.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_connectivity_tests(self) -> Callable[ + [reachability.ListConnectivityTestsRequest], + reachability.ListConnectivityTestsResponse]: + r"""Return a callable for the list connectivity tests method over gRPC. + + Lists all Connectivity Tests owned by a project. + + Returns: + Callable[[~.ListConnectivityTestsRequest], + ~.ListConnectivityTestsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connectivity_tests' not in self._stubs: + self._stubs['list_connectivity_tests'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/ListConnectivityTests', + request_serializer=reachability.ListConnectivityTestsRequest.serialize, + response_deserializer=reachability.ListConnectivityTestsResponse.deserialize, + ) + return self._stubs['list_connectivity_tests'] + + @property + def get_connectivity_test(self) -> Callable[ + [reachability.GetConnectivityTestRequest], + connectivity_test.ConnectivityTest]: + r"""Return a callable for the get connectivity test method over gRPC. + + Gets the details of a specific Connectivity Test. + + Returns: + Callable[[~.GetConnectivityTestRequest], + ~.ConnectivityTest]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connectivity_test' not in self._stubs: + self._stubs['get_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/GetConnectivityTest', + request_serializer=reachability.GetConnectivityTestRequest.serialize, + response_deserializer=connectivity_test.ConnectivityTest.deserialize, + ) + return self._stubs['get_connectivity_test'] + + @property + def create_connectivity_test(self) -> Callable[ + [reachability.CreateConnectivityTestRequest], + operations_pb2.Operation]: + r"""Return a callable for the create connectivity test method over gRPC. + + Creates a new Connectivity Test. After you create a test, the + reachability analysis is performed as part of the long running + operation, which completes when the analysis completes. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, containing non-existent resources in the + network, or you don't have read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + AMBIGUOUS. For more information, see the Connectivity Test + documentation. + + Returns: + Callable[[~.CreateConnectivityTestRequest], + ~.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_connectivity_test' not in self._stubs: + self._stubs['create_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/CreateConnectivityTest', + request_serializer=reachability.CreateConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_connectivity_test'] + + @property + def update_connectivity_test(self) -> Callable[ + [reachability.UpdateConnectivityTestRequest], + operations_pb2.Operation]: + r"""Return a callable for the update connectivity test method over gRPC. + + Updates the configuration of an existing ``ConnectivityTest``. + After you update a test, the reachability analysis is performed + as part of the long running operation, which completes when the + analysis completes. The Reachability state in the test resource + is updated with the new result. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, they contain non-existent resources in the + network, or the user does not have read permissions to the + network configurations of listed projects), then the + reachability result returns a value of UNKNOWN. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for + more details. + + Returns: + Callable[[~.UpdateConnectivityTestRequest], + ~.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_connectivity_test' not in self._stubs: + self._stubs['update_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/UpdateConnectivityTest', + request_serializer=reachability.UpdateConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_connectivity_test'] + + @property + def rerun_connectivity_test(self) -> Callable[ + [reachability.RerunConnectivityTestRequest], + operations_pb2.Operation]: + r"""Return a callable for the rerun connectivity test method over gRPC. + + Rerun an existing ``ConnectivityTest``. After the user triggers + the rerun, the reachability analysis is performed as part of the + long running operation, which completes when the analysis + completes. + + Even though the test configuration remains the same, the + reachability result may change due to underlying network + configuration changes. + + If the endpoint specifications in ``ConnectivityTest`` become + invalid (for example, specified resources are deleted in the + network, or you lost read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + Returns: + Callable[[~.RerunConnectivityTestRequest], + ~.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 'rerun_connectivity_test' not in self._stubs: + self._stubs['rerun_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/RerunConnectivityTest', + request_serializer=reachability.RerunConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rerun_connectivity_test'] + + @property + def delete_connectivity_test(self) -> Callable[ + [reachability.DeleteConnectivityTestRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete connectivity test method over gRPC. + + Deletes a specific ``ConnectivityTest``. + + Returns: + Callable[[~.DeleteConnectivityTestRequest], + ~.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_connectivity_test' not in self._stubs: + self._stubs['delete_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/DeleteConnectivityTest', + request_serializer=reachability.DeleteConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_connectivity_test'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ReachabilityServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..15d349b57214 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py @@ -0,0 +1,751 @@ +# -*- 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.location import locations_pb2 # type: ignore +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ReachabilityServiceGrpcTransport + + +class ReachabilityServiceGrpcAsyncIOTransport(ReachabilityServiceTransport): + """gRPC AsyncIO backend transport for ReachabilityService. + + The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + + 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 = 'networkmanagement.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 = 'networkmanagement.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: 'networkmanagement.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_connectivity_tests(self) -> Callable[ + [reachability.ListConnectivityTestsRequest], + Awaitable[reachability.ListConnectivityTestsResponse]]: + r"""Return a callable for the list connectivity tests method over gRPC. + + Lists all Connectivity Tests owned by a project. + + Returns: + Callable[[~.ListConnectivityTestsRequest], + Awaitable[~.ListConnectivityTestsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connectivity_tests' not in self._stubs: + self._stubs['list_connectivity_tests'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/ListConnectivityTests', + request_serializer=reachability.ListConnectivityTestsRequest.serialize, + response_deserializer=reachability.ListConnectivityTestsResponse.deserialize, + ) + return self._stubs['list_connectivity_tests'] + + @property + def get_connectivity_test(self) -> Callable[ + [reachability.GetConnectivityTestRequest], + Awaitable[connectivity_test.ConnectivityTest]]: + r"""Return a callable for the get connectivity test method over gRPC. + + Gets the details of a specific Connectivity Test. + + Returns: + Callable[[~.GetConnectivityTestRequest], + Awaitable[~.ConnectivityTest]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connectivity_test' not in self._stubs: + self._stubs['get_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/GetConnectivityTest', + request_serializer=reachability.GetConnectivityTestRequest.serialize, + response_deserializer=connectivity_test.ConnectivityTest.deserialize, + ) + return self._stubs['get_connectivity_test'] + + @property + def create_connectivity_test(self) -> Callable[ + [reachability.CreateConnectivityTestRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create connectivity test method over gRPC. + + Creates a new Connectivity Test. After you create a test, the + reachability analysis is performed as part of the long running + operation, which completes when the analysis completes. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, containing non-existent resources in the + network, or you don't have read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + AMBIGUOUS. For more information, see the Connectivity Test + documentation. + + Returns: + Callable[[~.CreateConnectivityTestRequest], + 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_connectivity_test' not in self._stubs: + self._stubs['create_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/CreateConnectivityTest', + request_serializer=reachability.CreateConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_connectivity_test'] + + @property + def update_connectivity_test(self) -> Callable[ + [reachability.UpdateConnectivityTestRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update connectivity test method over gRPC. + + Updates the configuration of an existing ``ConnectivityTest``. + After you update a test, the reachability analysis is performed + as part of the long running operation, which completes when the + analysis completes. The Reachability state in the test resource + is updated with the new result. + + If the endpoint specifications in ``ConnectivityTest`` are + invalid (for example, they contain non-existent resources in the + network, or the user does not have read permissions to the + network configurations of listed projects), then the + reachability result returns a value of UNKNOWN. + + If the endpoint specifications in ``ConnectivityTest`` are + incomplete, the reachability result returns a value of + ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for + more details. + + Returns: + Callable[[~.UpdateConnectivityTestRequest], + 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_connectivity_test' not in self._stubs: + self._stubs['update_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/UpdateConnectivityTest', + request_serializer=reachability.UpdateConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_connectivity_test'] + + @property + def rerun_connectivity_test(self) -> Callable[ + [reachability.RerunConnectivityTestRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rerun connectivity test method over gRPC. + + Rerun an existing ``ConnectivityTest``. After the user triggers + the rerun, the reachability analysis is performed as part of the + long running operation, which completes when the analysis + completes. + + Even though the test configuration remains the same, the + reachability result may change due to underlying network + configuration changes. + + If the endpoint specifications in ``ConnectivityTest`` become + invalid (for example, specified resources are deleted in the + network, or you lost read permissions to the network + configurations of listed projects), then the reachability result + returns a value of ``UNKNOWN``. + + Returns: + Callable[[~.RerunConnectivityTestRequest], + 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 'rerun_connectivity_test' not in self._stubs: + self._stubs['rerun_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/RerunConnectivityTest', + request_serializer=reachability.RerunConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rerun_connectivity_test'] + + @property + def delete_connectivity_test(self) -> Callable[ + [reachability.DeleteConnectivityTestRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete connectivity test method over gRPC. + + Deletes a specific ``ConnectivityTest``. + + Returns: + Callable[[~.DeleteConnectivityTestRequest], + 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_connectivity_test' not in self._stubs: + self._stubs['delete_connectivity_test'] = self.grpc_channel.unary_unary( + '/google.cloud.networkmanagement.v1.ReachabilityService/DeleteConnectivityTest', + request_serializer=reachability.DeleteConnectivityTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_connectivity_test'] + + 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_connectivity_tests: self._wrap_method( + self.list_connectivity_tests, + default_timeout=None, + client_info=client_info, + ), + self.get_connectivity_test: self._wrap_method( + self.get_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.create_connectivity_test: self._wrap_method( + self.create_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.update_connectivity_test: self._wrap_method( + self.update_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.rerun_connectivity_test: self._wrap_method( + self.rerun_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.delete_connectivity_test: self._wrap_method( + self.delete_connectivity_test, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self.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"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'ReachabilityServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py new file mode 100644 index 000000000000..aa84d74c181c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py @@ -0,0 +1,1714 @@ +# -*- 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.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseReachabilityServiceRestTransport +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 ReachabilityServiceRestInterceptor: + """Interceptor for ReachabilityService. + + 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 ReachabilityServiceRestTransport. + + .. code-block:: python + class MyCustomReachabilityServiceInterceptor(ReachabilityServiceRestInterceptor): + def pre_create_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_connectivity_tests(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_connectivity_tests(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_rerun_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_rerun_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ReachabilityServiceRestTransport(interceptor=MyCustomReachabilityServiceInterceptor()) + client = ReachabilityServiceClient(transport=transport) + + + """ + def pre_create_connectivity_test(self, request: reachability.CreateConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.CreateConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_create_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_delete_connectivity_test(self, request: reachability.DeleteConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.DeleteConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_delete_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_get_connectivity_test(self, request: reachability.GetConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.GetConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_get_connectivity_test(self, response: connectivity_test.ConnectivityTest) -> connectivity_test.ConnectivityTest: + """Post-rpc interceptor for get_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_list_connectivity_tests(self, request: reachability.ListConnectivityTestsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.ListConnectivityTestsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_connectivity_tests + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_list_connectivity_tests(self, response: reachability.ListConnectivityTestsResponse) -> reachability.ListConnectivityTestsResponse: + """Post-rpc interceptor for list_connectivity_tests + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_rerun_connectivity_test(self, request: reachability.RerunConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.RerunConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for rerun_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_rerun_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for rerun_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_update_connectivity_test(self, request: reachability.UpdateConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.UpdateConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_update_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ReachabilityServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ReachabilityServiceRestInterceptor + + +class ReachabilityServiceRestTransport(_BaseReachabilityServiceRestTransport): + """REST backend synchronous transport for ReachabilityService. + + The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + + 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 = 'networkmanagement.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[ReachabilityServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkmanagement.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 ReachabilityServiceRestInterceptor() + 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/global/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/global/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/global/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/global}/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 _CreateConnectivityTest(_BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.CreateConnectivityTest") + + @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: reachability.CreateConnectivityTestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create connectivity test method over HTTP. + + Args: + request (~.reachability.CreateConnectivityTestRequest): + The request object. Request for the ``CreateConnectivityTest`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_http_options() + request, metadata = self._interceptor.pre_create_connectivity_test(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._CreateConnectivityTest._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_connectivity_test(resp) + return resp + + class _DeleteConnectivityTest(_BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.DeleteConnectivityTest") + + @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: reachability.DeleteConnectivityTestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete connectivity test method over HTTP. + + Args: + request (~.reachability.DeleteConnectivityTestRequest): + The request object. Request for the ``DeleteConnectivityTest`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_http_options() + request, metadata = self._interceptor.pre_delete_connectivity_test(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._DeleteConnectivityTest._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_connectivity_test(resp) + return resp + + class _GetConnectivityTest(_BaseReachabilityServiceRestTransport._BaseGetConnectivityTest, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.GetConnectivityTest") + + @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: reachability.GetConnectivityTestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> connectivity_test.ConnectivityTest: + r"""Call the get connectivity test method over HTTP. + + Args: + request (~.reachability.GetConnectivityTestRequest): + The request object. Request for the ``GetConnectivityTest`` 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: + ~.connectivity_test.ConnectivityTest: + A Connectivity Test for a network + reachability analysis. + + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_http_options() + request, metadata = self._interceptor.pre_get_connectivity_test(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._GetConnectivityTest._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 = connectivity_test.ConnectivityTest() + pb_resp = connectivity_test.ConnectivityTest.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_connectivity_test(resp) + return resp + + class _ListConnectivityTests(_BaseReachabilityServiceRestTransport._BaseListConnectivityTests, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.ListConnectivityTests") + + @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: reachability.ListConnectivityTestsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> reachability.ListConnectivityTestsResponse: + r"""Call the list connectivity tests method over HTTP. + + Args: + request (~.reachability.ListConnectivityTestsRequest): + The request object. Request for the ``ListConnectivityTests`` 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: + ~.reachability.ListConnectivityTestsResponse: + Response for the ``ListConnectivityTests`` method. + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_http_options() + request, metadata = self._interceptor.pre_list_connectivity_tests(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._ListConnectivityTests._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 = reachability.ListConnectivityTestsResponse() + pb_resp = reachability.ListConnectivityTestsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_connectivity_tests(resp) + return resp + + class _RerunConnectivityTest(_BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.RerunConnectivityTest") + + @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: reachability.RerunConnectivityTestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the rerun connectivity test method over HTTP. + + Args: + request (~.reachability.RerunConnectivityTestRequest): + The request object. Request for the ``RerunConnectivityTest`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_http_options() + request, metadata = self._interceptor.pre_rerun_connectivity_test(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._RerunConnectivityTest._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_rerun_connectivity_test(resp) + return resp + + class _UpdateConnectivityTest(_BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.UpdateConnectivityTest") + + @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: reachability.UpdateConnectivityTestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update connectivity test method over HTTP. + + Args: + request (~.reachability.UpdateConnectivityTestRequest): + The request object. Request for the ``UpdateConnectivityTest`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_http_options() + request, metadata = self._interceptor.pre_update_connectivity_test(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._UpdateConnectivityTest._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_connectivity_test(resp) + return resp + + @property + def create_connectivity_test(self) -> Callable[ + [reachability.CreateConnectivityTestRequest], + 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._CreateConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_connectivity_test(self) -> Callable[ + [reachability.DeleteConnectivityTestRequest], + 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._DeleteConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_connectivity_test(self) -> Callable[ + [reachability.GetConnectivityTestRequest], + connectivity_test.ConnectivityTest]: + # 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._GetConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_connectivity_tests(self) -> Callable[ + [reachability.ListConnectivityTestsRequest], + reachability.ListConnectivityTestsResponse]: + # 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._ListConnectivityTests(self._session, self._host, self._interceptor) # type: ignore + + @property + def rerun_connectivity_test(self) -> Callable[ + [reachability.RerunConnectivityTestRequest], + 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._RerunConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_connectivity_test(self) -> Callable[ + [reachability.UpdateConnectivityTestRequest], + 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._UpdateConnectivityTest(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(_BaseReachabilityServiceRestTransport._BaseGetLocation, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseListLocations, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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 get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseReachabilityServiceRestTransport._BaseGetIamPolicy, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseReachabilityServiceRestTransport._BaseSetIamPolicy, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseReachabilityServiceRestTransport._BaseTestIamPermissions, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseReachabilityServiceRestTransport._BaseCancelOperation, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseDeleteOperation, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseGetOperation, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseListOperations, ReachabilityServiceRestStub): + def __hash__(self): + return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseReachabilityServiceRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseReachabilityServiceRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + # Send the request + response = ReachabilityServiceRestTransport._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__=( + 'ReachabilityServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py new file mode 100644 index 000000000000..7dd2991844be --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py @@ -0,0 +1,588 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseReachabilityServiceRestTransport(ReachabilityServiceTransport): + """Base REST backend transport for ReachabilityService. + + 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 = 'networkmanagement.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: 'networkmanagement.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 _BaseCreateConnectivityTest: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "testId" : "", } + + @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/global}/connectivityTests', + 'body': 'resource', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.CreateConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteConnectivityTest: + 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/global/connectivityTests/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.DeleteConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetConnectivityTest: + 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/global/connectivityTests/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.GetConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListConnectivityTests: + 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/global}/connectivityTests', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.ListConnectivityTestsRequest.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(_BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRerunConnectivityTest: + 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/global/connectivityTests/*}:rerun', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.RerunConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateConnectivityTest: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{resource.name=projects/*/locations/global/connectivityTests/*}', + 'body': 'resource', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reachability.UpdateConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/global/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/global/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/global/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/global}/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__=( + '_BaseReachabilityServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py new file mode 100644 index 000000000000..ce14d0c9af68 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py @@ -0,0 +1,114 @@ +# -*- 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 .connectivity_test import ( + ConnectivityTest, + Endpoint, + LatencyDistribution, + LatencyPercentile, + ProbingDetails, + ReachabilityDetails, +) +from .reachability import ( + CreateConnectivityTestRequest, + DeleteConnectivityTestRequest, + GetConnectivityTestRequest, + ListConnectivityTestsRequest, + ListConnectivityTestsResponse, + OperationMetadata, + RerunConnectivityTestRequest, + UpdateConnectivityTestRequest, +) +from .trace import ( + AbortInfo, + AppEngineVersionInfo, + CloudFunctionInfo, + CloudRunRevisionInfo, + CloudSQLInstanceInfo, + DeliverInfo, + DropInfo, + EndpointInfo, + FirewallInfo, + ForwardInfo, + ForwardingRuleInfo, + GKEMasterInfo, + GoogleServiceInfo, + InstanceInfo, + LoadBalancerBackend, + LoadBalancerBackendInfo, + LoadBalancerInfo, + NatInfo, + NetworkInfo, + ProxyConnectionInfo, + RedisClusterInfo, + RedisInstanceInfo, + RouteInfo, + ServerlessNegInfo, + Step, + StorageBucketInfo, + Trace, + VpcConnectorInfo, + VpnGatewayInfo, + VpnTunnelInfo, + LoadBalancerType, +) + +__all__ = ( + 'ConnectivityTest', + 'Endpoint', + 'LatencyDistribution', + 'LatencyPercentile', + 'ProbingDetails', + 'ReachabilityDetails', + 'CreateConnectivityTestRequest', + 'DeleteConnectivityTestRequest', + 'GetConnectivityTestRequest', + 'ListConnectivityTestsRequest', + 'ListConnectivityTestsResponse', + 'OperationMetadata', + 'RerunConnectivityTestRequest', + 'UpdateConnectivityTestRequest', + 'AbortInfo', + 'AppEngineVersionInfo', + 'CloudFunctionInfo', + 'CloudRunRevisionInfo', + 'CloudSQLInstanceInfo', + 'DeliverInfo', + 'DropInfo', + 'EndpointInfo', + 'FirewallInfo', + 'ForwardInfo', + 'ForwardingRuleInfo', + 'GKEMasterInfo', + 'GoogleServiceInfo', + 'InstanceInfo', + 'LoadBalancerBackend', + 'LoadBalancerBackendInfo', + 'LoadBalancerInfo', + 'NatInfo', + 'NetworkInfo', + 'ProxyConnectionInfo', + 'RedisClusterInfo', + 'RedisInstanceInfo', + 'RouteInfo', + 'ServerlessNegInfo', + 'Step', + 'StorageBucketInfo', + 'Trace', + 'VpcConnectorInfo', + 'VpnGatewayInfo', + 'VpnTunnelInfo', + 'LoadBalancerType', +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py new file mode 100644 index 000000000000..9e8dc38fbf27 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py @@ -0,0 +1,753 @@ +# -*- 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.network_management_v1.types import trace +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networkmanagement.v1', + manifest={ + 'ConnectivityTest', + 'Endpoint', + 'ReachabilityDetails', + 'LatencyPercentile', + 'LatencyDistribution', + 'ProbingDetails', + }, +) + + +class ConnectivityTest(proto.Message): + r"""A Connectivity Test for a network reachability analysis. + + Attributes: + name (str): + Identifier. Unique name of the resource using the form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + description (str): + The user-supplied description of the + Connectivity Test. Maximum of 512 characters. + source (google.cloud.network_management_v1.types.Endpoint): + Required. Source specification of the + Connectivity Test. + You can use a combination of source IP address, + virtual machine (VM) instance, or Compute Engine + network to uniquely identify the source + location. + + Examples: + + If the source IP address is an internal IP + address within a Google Cloud Virtual Private + Cloud (VPC) network, then you must also specify + the VPC network. Otherwise, specify the VM + instance, which already contains its internal IP + address and VPC network information. + + If the source of the test is within an + on-premises network, then you must provide the + destination VPC network. + + If the source endpoint is a Compute Engine VM + instance with multiple network interfaces, the + instance itself is not sufficient to identify + the endpoint. So, you must also specify the + source IP address or VPC network. + + A reachability analysis proceeds even if the + source location is ambiguous. However, the test + result may include endpoints that you don't + intend to test. + destination (google.cloud.network_management_v1.types.Endpoint): + Required. Destination specification of the + Connectivity Test. + You can use a combination of destination IP + address, Compute Engine VM instance, or VPC + network to uniquely identify the destination + location. + + Even if the destination IP address is not + unique, the source IP location is unique. + Usually, the analysis can infer the destination + endpoint from route information. + + If the destination you specify is a VM instance + and the instance has multiple network + interfaces, then you must also specify either a + destination IP address or VPC network to + identify the destination interface. + + A reachability analysis proceeds even if the + destination location is ambiguous. However, the + result can include endpoints that you don't + intend to test. + protocol (str): + IP Protocol of the test. When not provided, + "TCP" is assumed. + related_projects (MutableSequence[str]): + Other projects that may be relevant for + reachability analysis. This is applicable to + scenarios where a test can cross project + boundaries. + display_name (str): + Output only. The display name of a + Connectivity Test. + labels (MutableMapping[str, str]): + Resource labels to represent user-provided + metadata. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the test was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the test's + configuration was updated. + reachability_details (google.cloud.network_management_v1.types.ReachabilityDetails): + Output only. The reachability details of this + test from the latest run. The details are + updated when creating a new test, updating an + existing test, or triggering a one-time rerun of + an existing test. + probing_details (google.cloud.network_management_v1.types.ProbingDetails): + Output only. The probing details of this test + from the latest run, present for applicable + tests only. The details are updated when + creating a new test, updating an existing test, + or triggering a one-time rerun of an existing + test. + round_trip (bool): + Whether run analysis for the return path from + destination to source. Default value is false. + return_reachability_details (google.cloud.network_management_v1.types.ReachabilityDetails): + Output only. The reachability details of this + test from the latest run for the return path. + The details are updated when creating a new + test, updating an existing test, or triggering a + one-time rerun of an existing test. + bypass_firewall_checks (bool): + Whether the test should skip firewall + checking. If not provided, we assume false. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + source: 'Endpoint' = proto.Field( + proto.MESSAGE, + number=3, + message='Endpoint', + ) + destination: 'Endpoint' = proto.Field( + proto.MESSAGE, + number=4, + message='Endpoint', + ) + protocol: str = proto.Field( + proto.STRING, + number=5, + ) + related_projects: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + display_name: str = proto.Field( + proto.STRING, + number=7, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + reachability_details: 'ReachabilityDetails' = proto.Field( + proto.MESSAGE, + number=12, + message='ReachabilityDetails', + ) + probing_details: 'ProbingDetails' = proto.Field( + proto.MESSAGE, + number=14, + message='ProbingDetails', + ) + round_trip: bool = proto.Field( + proto.BOOL, + number=15, + ) + return_reachability_details: 'ReachabilityDetails' = proto.Field( + proto.MESSAGE, + number=16, + message='ReachabilityDetails', + ) + bypass_firewall_checks: bool = proto.Field( + proto.BOOL, + number=17, + ) + + +class Endpoint(proto.Message): + r"""Source or destination of the Connectivity Test. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + ip_address (str): + The IP address of the endpoint, which can be + an external or internal IP. + port (int): + The IP protocol port of the endpoint. + Only applicable when protocol is TCP or UDP. + instance (str): + A Compute Engine instance URI. + forwarding_rule (str): + A forwarding rule and its corresponding IP + address represent the frontend configuration of + a Google Cloud load balancer. Forwarding rules + are also used for protocol forwarding, Private + Service Connect and other network services to + provide forwarding information in the control + plane. Format: + + projects/{project}/global/forwardingRules/{id} + or + projects/{project}/regions/{region}/forwardingRules/{id} + forwarding_rule_target (google.cloud.network_management_v1.types.Endpoint.ForwardingRuleTarget): + Output only. Specifies the type of the target + of the forwarding rule. + + This field is a member of `oneof`_ ``_forwarding_rule_target``. + load_balancer_id (str): + Output only. ID of the load balancer the + forwarding rule points to. Empty for forwarding + rules not related to load balancers. + + This field is a member of `oneof`_ ``_load_balancer_id``. + load_balancer_type (google.cloud.network_management_v1.types.LoadBalancerType): + Output only. Type of the load balancer the + forwarding rule points to. + + This field is a member of `oneof`_ ``_load_balancer_type``. + gke_master_cluster (str): + A cluster URI for `Google Kubernetes Engine cluster control + plane `__. + fqdn (str): + DNS endpoint of `Google Kubernetes Engine cluster control + plane `__. + Requires gke_master_cluster to be set, can't be used + simultaneoulsly with ip_address or network. Applicable only + to destination endpoint. + cloud_sql_instance (str): + A `Cloud SQL `__ instance URI. + redis_instance (str): + A `Redis + Instance `__ + URI. + redis_cluster (str): + A `Redis + Cluster `__ + URI. + cloud_function (google.cloud.network_management_v1.types.Endpoint.CloudFunctionEndpoint): + A `Cloud Function `__. + app_engine_version (google.cloud.network_management_v1.types.Endpoint.AppEngineVersionEndpoint): + An `App Engine `__ + `service + version `__. + cloud_run_revision (google.cloud.network_management_v1.types.Endpoint.CloudRunRevisionEndpoint): + A `Cloud Run `__ + `revision `__ + network (str): + A Compute Engine network URI. + network_type (google.cloud.network_management_v1.types.Endpoint.NetworkType): + Type of the network where the endpoint is + located. Applicable only to source endpoint, as + destination network type can be inferred from + the source. + project_id (str): + Project ID where the endpoint is located. + The Project ID can be derived from the URI if + you provide a VM instance or network URI. + The following are two cases where you must + provide the project ID: + + 1. Only the IP address is specified, and the IP + address is within a Google Cloud project. + 2. When you are using Shared VPC and the IP + address that you provide is from the service + project. In this case, the network that the + IP address resides in is defined in the host + project. + """ + class NetworkType(proto.Enum): + r"""The type definition of an endpoint's network. Use one of the + following choices: + + Values: + NETWORK_TYPE_UNSPECIFIED (0): + Default type if unspecified. + GCP_NETWORK (1): + A network hosted within Google Cloud. + To receive more detailed output, specify the URI + for the source or destination network. + NON_GCP_NETWORK (2): + A network hosted outside of Google Cloud. + This can be an on-premises network, or a network + hosted by another cloud provider. + """ + NETWORK_TYPE_UNSPECIFIED = 0 + GCP_NETWORK = 1 + NON_GCP_NETWORK = 2 + + class ForwardingRuleTarget(proto.Enum): + r"""Type of the target of a forwarding rule. + + Values: + FORWARDING_RULE_TARGET_UNSPECIFIED (0): + Forwarding rule target is unknown. + INSTANCE (1): + Compute Engine instance for protocol + forwarding. + LOAD_BALANCER (2): + Load Balancer. The specific type can be found from + [load_balancer_type] + [google.cloud.networkmanagement.v1.Endpoint.load_balancer_type]. + VPN_GATEWAY (3): + Classic Cloud VPN Gateway. + PSC (4): + Forwarding Rule is a Private Service Connect + endpoint. + """ + FORWARDING_RULE_TARGET_UNSPECIFIED = 0 + INSTANCE = 1 + LOAD_BALANCER = 2 + VPN_GATEWAY = 3 + PSC = 4 + + class CloudFunctionEndpoint(proto.Message): + r"""Wrapper for Cloud Function attributes. + + Attributes: + uri (str): + A `Cloud Function `__ + name. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + class AppEngineVersionEndpoint(proto.Message): + r"""Wrapper for the App Engine service version attributes. + + Attributes: + uri (str): + An `App Engine `__ + `service + version `__ + name. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + class CloudRunRevisionEndpoint(proto.Message): + r"""Wrapper for Cloud Run revision attributes. + + Attributes: + uri (str): + A `Cloud Run `__ + `revision `__ + URI. The format is: + projects/{project}/locations/{location}/revisions/{revision} + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + ip_address: str = proto.Field( + proto.STRING, + number=1, + ) + port: int = proto.Field( + proto.INT32, + number=2, + ) + instance: str = proto.Field( + proto.STRING, + number=3, + ) + forwarding_rule: str = proto.Field( + proto.STRING, + number=13, + ) + forwarding_rule_target: ForwardingRuleTarget = proto.Field( + proto.ENUM, + number=14, + optional=True, + enum=ForwardingRuleTarget, + ) + load_balancer_id: str = proto.Field( + proto.STRING, + number=15, + optional=True, + ) + load_balancer_type: trace.LoadBalancerType = proto.Field( + proto.ENUM, + number=16, + optional=True, + enum=trace.LoadBalancerType, + ) + gke_master_cluster: str = proto.Field( + proto.STRING, + number=7, + ) + fqdn: str = proto.Field( + proto.STRING, + number=19, + ) + cloud_sql_instance: str = proto.Field( + proto.STRING, + number=8, + ) + redis_instance: str = proto.Field( + proto.STRING, + number=17, + ) + redis_cluster: str = proto.Field( + proto.STRING, + number=18, + ) + cloud_function: CloudFunctionEndpoint = proto.Field( + proto.MESSAGE, + number=10, + message=CloudFunctionEndpoint, + ) + app_engine_version: AppEngineVersionEndpoint = proto.Field( + proto.MESSAGE, + number=11, + message=AppEngineVersionEndpoint, + ) + cloud_run_revision: CloudRunRevisionEndpoint = proto.Field( + proto.MESSAGE, + number=12, + message=CloudRunRevisionEndpoint, + ) + network: str = proto.Field( + proto.STRING, + number=4, + ) + network_type: NetworkType = proto.Field( + proto.ENUM, + number=5, + enum=NetworkType, + ) + project_id: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ReachabilityDetails(proto.Message): + r"""Results of the configuration analysis from the last run of + the test. + + Attributes: + result (google.cloud.network_management_v1.types.ReachabilityDetails.Result): + The overall result of the test's + configuration analysis. + verify_time (google.protobuf.timestamp_pb2.Timestamp): + The time of the configuration analysis. + error (google.rpc.status_pb2.Status): + The details of a failure or a cancellation of + reachability analysis. + traces (MutableSequence[google.cloud.network_management_v1.types.Trace]): + Result may contain a list of traces if a test + has multiple possible paths in the network, such + as when destination endpoint is a load balancer + with multiple backends. + """ + class Result(proto.Enum): + r"""The overall result of the test's configuration analysis. + + Values: + RESULT_UNSPECIFIED (0): + No result was specified. + REACHABLE (1): + Possible scenarios are: + + - The configuration analysis determined that a packet + originating from the source is expected to reach the + destination. + - The analysis didn't complete because the user lacks + permission for some of the resources in the trace. + However, at the time the user's permission became + insufficient, the trace had been successful so far. + UNREACHABLE (2): + A packet originating from the source is + expected to be dropped before reaching the + destination. + AMBIGUOUS (4): + The source and destination endpoints do not + uniquely identify the test location in the + network, and the reachability result contains + multiple traces. For some traces, a packet could + be delivered, and for others, it would not be. + This result is also assigned to configuration + analysis of return path if on its own it should + be REACHABLE, but configuration analysis of + forward path is AMBIGUOUS. + UNDETERMINED (5): + The configuration analysis did not complete. Possible + reasons are: + + - A permissions error occurred--for example, the user might + not have read permission for all of the resources named + in the test. + - An internal error occurred. + - The analyzer received an invalid or unsupported argument + or was unable to identify a known endpoint. + """ + RESULT_UNSPECIFIED = 0 + REACHABLE = 1 + UNREACHABLE = 2 + AMBIGUOUS = 4 + UNDETERMINED = 5 + + result: Result = proto.Field( + proto.ENUM, + number=1, + enum=Result, + ) + verify_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + traces: MutableSequence[trace.Trace] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=trace.Trace, + ) + + +class LatencyPercentile(proto.Message): + r"""Latency percentile rank and value. + + Attributes: + percent (int): + Percentage of samples this data point applies + to. + latency_micros (int): + percent-th percentile of latency observed, in + microseconds. Fraction of percent/100 of samples + have latency lower or equal to the value of this + field. + """ + + percent: int = proto.Field( + proto.INT32, + number=1, + ) + latency_micros: int = proto.Field( + proto.INT64, + number=2, + ) + + +class LatencyDistribution(proto.Message): + r"""Describes measured latency distribution. + + Attributes: + latency_percentiles (MutableSequence[google.cloud.network_management_v1.types.LatencyPercentile]): + Representative latency percentiles. + """ + + latency_percentiles: MutableSequence['LatencyPercentile'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='LatencyPercentile', + ) + + +class ProbingDetails(proto.Message): + r"""Results of active probing from the last run of the test. + + Attributes: + result (google.cloud.network_management_v1.types.ProbingDetails.ProbingResult): + The overall result of active probing. + verify_time (google.protobuf.timestamp_pb2.Timestamp): + The time that reachability was assessed + through active probing. + error (google.rpc.status_pb2.Status): + Details about an internal failure or the + cancellation of active probing. + abort_cause (google.cloud.network_management_v1.types.ProbingDetails.ProbingAbortCause): + The reason probing was aborted. + sent_probe_count (int): + Number of probes sent. + successful_probe_count (int): + Number of probes that reached the + destination. + endpoint_info (google.cloud.network_management_v1.types.EndpointInfo): + The source and destination endpoints derived + from the test input and used for active probing. + probing_latency (google.cloud.network_management_v1.types.LatencyDistribution): + Latency as measured by active probing in one + direction: from the source to the destination + endpoint. + destination_egress_location (google.cloud.network_management_v1.types.ProbingDetails.EdgeLocation): + The EdgeLocation from which a packet destined + for/originating from the internet will egress/ingress the + Google network. This will only be populated for a + connectivity test which has an internet destination/source + address. The absence of this field *must not* be used as an + indication that the destination/source is part of the Google + network. + """ + class ProbingResult(proto.Enum): + r"""Overall probing result of the test. + + Values: + PROBING_RESULT_UNSPECIFIED (0): + No result was specified. + REACHABLE (1): + At least 95% of packets reached the + destination. + UNREACHABLE (2): + No packets reached the destination. + REACHABILITY_INCONSISTENT (3): + Less than 95% of packets reached the + destination. + UNDETERMINED (4): + Reachability could not be determined. Possible reasons are: + + - The user lacks permission to access some of the network + resources required to run the test. + - No valid source endpoint could be derived from the + request. + - An internal error occurred. + """ + PROBING_RESULT_UNSPECIFIED = 0 + REACHABLE = 1 + UNREACHABLE = 2 + REACHABILITY_INCONSISTENT = 3 + UNDETERMINED = 4 + + class ProbingAbortCause(proto.Enum): + r"""Abort cause types. + + Values: + PROBING_ABORT_CAUSE_UNSPECIFIED (0): + No reason was specified. + PERMISSION_DENIED (1): + The user lacks permission to access some of + the network resources required to run the test. + NO_SOURCE_LOCATION (2): + No valid source endpoint could be derived + from the request. + """ + PROBING_ABORT_CAUSE_UNSPECIFIED = 0 + PERMISSION_DENIED = 1 + NO_SOURCE_LOCATION = 2 + + class EdgeLocation(proto.Message): + r"""Representation of a network edge location as per + https://cloud.google.com/vpc/docs/edge-locations. + + Attributes: + metropolitan_area (str): + Name of the metropolitan area. + """ + + metropolitan_area: str = proto.Field( + proto.STRING, + number=1, + ) + + result: ProbingResult = proto.Field( + proto.ENUM, + number=1, + enum=ProbingResult, + ) + verify_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + abort_cause: ProbingAbortCause = proto.Field( + proto.ENUM, + number=4, + enum=ProbingAbortCause, + ) + sent_probe_count: int = proto.Field( + proto.INT32, + number=5, + ) + successful_probe_count: int = proto.Field( + proto.INT32, + number=6, + ) + endpoint_info: trace.EndpointInfo = proto.Field( + proto.MESSAGE, + number=7, + message=trace.EndpointInfo, + ) + probing_latency: 'LatencyDistribution' = proto.Field( + proto.MESSAGE, + number=8, + message='LatencyDistribution', + ) + destination_egress_location: EdgeLocation = proto.Field( + proto.MESSAGE, + number=9, + message=EdgeLocation, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py new file mode 100644 index 000000000000..ed3cdf469712 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py @@ -0,0 +1,293 @@ +# -*- 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.network_management_v1.types import connectivity_test +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networkmanagement.v1', + manifest={ + 'ListConnectivityTestsRequest', + 'ListConnectivityTestsResponse', + 'GetConnectivityTestRequest', + 'CreateConnectivityTestRequest', + 'UpdateConnectivityTestRequest', + 'DeleteConnectivityTestRequest', + 'RerunConnectivityTestRequest', + 'OperationMetadata', + }, +) + + +class ListConnectivityTestsRequest(proto.Message): + r"""Request for the ``ListConnectivityTests`` method. + + Attributes: + parent (str): + Required. The parent resource of the Connectivity Tests: + ``projects/{project_id}/locations/global`` + page_size (int): + Number of ``ConnectivityTests`` to return. + page_token (str): + Page token from an earlier query, as returned in + ``next_page_token``. + filter (str): + Lists the ``ConnectivityTests`` that match the filter + expression. A filter expression filters the resources listed + in the response. The expression must be of the form + `` `` where operators: ``<``, + ``>``, ``<=``, ``>=``, ``!=``, ``=``, ``:`` are supported + (colon ``:`` represents a HAS operator which is roughly + synonymous with equality). can refer to a proto or JSON + field, or a synthetic field. Field names can be camelCase or + snake_case. + + Examples: + + - Filter by name: name = + "projects/proj-1/locations/global/connectivityTests/test-1 + + - Filter by labels: + + - Resources that have a key called ``foo`` labels.foo:\* + - Resources that have a key called ``foo`` whose value + is ``bar`` labels.foo = bar + order_by (str): + Field to use to sort the list. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListConnectivityTestsResponse(proto.Message): + r"""Response for the ``ListConnectivityTests`` method. + + Attributes: + resources (MutableSequence[google.cloud.network_management_v1.types.ConnectivityTest]): + List of Connectivity Tests. + next_page_token (str): + Page token to fetch the next set of + Connectivity Tests. + unreachable (MutableSequence[str]): + Locations that could not be reached (when querying all + locations with ``-``). + """ + + @property + def raw_page(self): + return self + + resources: MutableSequence[connectivity_test.ConnectivityTest] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=connectivity_test.ConnectivityTest, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetConnectivityTestRequest(proto.Message): + r"""Request for the ``GetConnectivityTest`` method. + + Attributes: + name (str): + Required. ``ConnectivityTest`` resource name using the form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateConnectivityTestRequest(proto.Message): + r"""Request for the ``CreateConnectivityTest`` method. + + Attributes: + parent (str): + Required. The parent resource of the Connectivity Test to + create: ``projects/{project_id}/locations/global`` + test_id (str): + Required. The logical name of the Connectivity Test in your + project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-40 characters. + - Must end with a number or a letter. + - Must be unique within the customer project + resource (google.cloud.network_management_v1.types.ConnectivityTest): + Required. A ``ConnectivityTest`` resource + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + test_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource: connectivity_test.ConnectivityTest = proto.Field( + proto.MESSAGE, + number=3, + message=connectivity_test.ConnectivityTest, + ) + + +class UpdateConnectivityTestRequest(proto.Message): + r"""Request for the ``UpdateConnectivityTest`` method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. At least + one path must be supplied in this field. + resource (google.cloud.network_management_v1.types.ConnectivityTest): + Required. Only fields specified in update_mask are updated. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + resource: connectivity_test.ConnectivityTest = proto.Field( + proto.MESSAGE, + number=2, + message=connectivity_test.ConnectivityTest, + ) + + +class DeleteConnectivityTestRequest(proto.Message): + r"""Request for the ``DeleteConnectivityTest`` method. + + Attributes: + name (str): + Required. Connectivity Test resource name using the form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RerunConnectivityTestRequest(proto.Message): + r"""Request for the ``RerunConnectivityTest`` method. + + Attributes: + name (str): + Required. Connectivity Test resource name using the form: + ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class OperationMetadata(proto.Message): + r"""Metadata describing an [Operation][google.longrunning.Operation] + + 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): + Target of the operation - for example + projects/project-1/locations/global/connectivityTests/test-1 + verb (str): + Name of the verb executed by the operation. + status_detail (str): + Human-readable status of the operation, if + any. + cancel_requested (bool): + Specifies if cancellation was requested for + the operation. + api_version (str): + API version. + """ + + 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_detail: str = proto.Field( + proto.STRING, + number=5, + ) + cancel_requested: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py new file mode 100644 index 000000000000..78741f3894e1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py @@ -0,0 +1,3164 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.networkmanagement.v1', + manifest={ + 'LoadBalancerType', + 'Trace', + 'Step', + 'InstanceInfo', + 'NetworkInfo', + 'FirewallInfo', + 'RouteInfo', + 'GoogleServiceInfo', + 'ForwardingRuleInfo', + 'LoadBalancerInfo', + 'LoadBalancerBackend', + 'VpnGatewayInfo', + 'VpnTunnelInfo', + 'EndpointInfo', + 'DeliverInfo', + 'ForwardInfo', + 'AbortInfo', + 'DropInfo', + 'GKEMasterInfo', + 'CloudSQLInstanceInfo', + 'RedisInstanceInfo', + 'RedisClusterInfo', + 'CloudFunctionInfo', + 'CloudRunRevisionInfo', + 'AppEngineVersionInfo', + 'VpcConnectorInfo', + 'NatInfo', + 'ProxyConnectionInfo', + 'LoadBalancerBackendInfo', + 'StorageBucketInfo', + 'ServerlessNegInfo', + }, +) + + +class LoadBalancerType(proto.Enum): + r"""Type of a load balancer. For more information, see `Summary of + Google Cloud load + balancers `__. + + Values: + LOAD_BALANCER_TYPE_UNSPECIFIED (0): + Forwarding rule points to a different target + than a load balancer or a load balancer type is + unknown. + HTTPS_ADVANCED_LOAD_BALANCER (1): + Global external HTTP(S) load balancer. + HTTPS_LOAD_BALANCER (2): + Global external HTTP(S) load balancer + (classic) + REGIONAL_HTTPS_LOAD_BALANCER (3): + Regional external HTTP(S) load balancer. + INTERNAL_HTTPS_LOAD_BALANCER (4): + Internal HTTP(S) load balancer. + SSL_PROXY_LOAD_BALANCER (5): + External SSL proxy load balancer. + TCP_PROXY_LOAD_BALANCER (6): + External TCP proxy load balancer. + INTERNAL_TCP_PROXY_LOAD_BALANCER (7): + Internal regional TCP proxy load balancer. + NETWORK_LOAD_BALANCER (8): + External TCP/UDP Network load balancer. + LEGACY_NETWORK_LOAD_BALANCER (9): + Target-pool based external TCP/UDP Network + load balancer. + TCP_UDP_INTERNAL_LOAD_BALANCER (10): + Internal TCP/UDP load balancer. + """ + LOAD_BALANCER_TYPE_UNSPECIFIED = 0 + HTTPS_ADVANCED_LOAD_BALANCER = 1 + HTTPS_LOAD_BALANCER = 2 + REGIONAL_HTTPS_LOAD_BALANCER = 3 + INTERNAL_HTTPS_LOAD_BALANCER = 4 + SSL_PROXY_LOAD_BALANCER = 5 + TCP_PROXY_LOAD_BALANCER = 6 + INTERNAL_TCP_PROXY_LOAD_BALANCER = 7 + NETWORK_LOAD_BALANCER = 8 + LEGACY_NETWORK_LOAD_BALANCER = 9 + TCP_UDP_INTERNAL_LOAD_BALANCER = 10 + + +class Trace(proto.Message): + r"""Trace represents one simulated packet forwarding path. + + - Each trace contains multiple ordered steps. + - Each step is in a particular state with associated configuration. + - State is categorized as final or non-final states. + - Each final state has a reason associated. + - Each trace must end with a final state (the last step). + + :: + + |---------------------Trace----------------------| + Step1(State) Step2(State) --- StepN(State(final)) + + Attributes: + endpoint_info (google.cloud.network_management_v1.types.EndpointInfo): + Derived from the source and destination endpoints definition + specified by user request, and validated by the data plane + model. If there are multiple traces starting from different + source locations, then the endpoint_info may be different + between traces. + steps (MutableSequence[google.cloud.network_management_v1.types.Step]): + A trace of a test contains multiple steps + from the initial state to the final state + (delivered, dropped, forwarded, or aborted). + + The steps are ordered by the processing sequence + within the simulated network state machine. It + is critical to preserve the order of the steps + and avoid reordering or sorting them. + forward_trace_id (int): + ID of trace. For forward traces, this ID is + unique for each trace. For return traces, it + matches ID of associated forward trace. A single + forward trace can be associated with none, one + or more than one return trace. + """ + + endpoint_info: 'EndpointInfo' = proto.Field( + proto.MESSAGE, + number=1, + message='EndpointInfo', + ) + steps: MutableSequence['Step'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Step', + ) + forward_trace_id: int = proto.Field( + proto.INT32, + number=4, + ) + + +class Step(proto.Message): + r"""A simulated forwarding path is composed of multiple steps. + Each step has a well-defined state and an associated + configuration. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + description (str): + A description of the step. Usually this is a + summary of the state. + state (google.cloud.network_management_v1.types.Step.State): + Each step is in one of the pre-defined + states. + causes_drop (bool): + This is a step that leads to the final state + Drop. + project_id (str): + Project ID that contains the configuration + this step is validating. + instance (google.cloud.network_management_v1.types.InstanceInfo): + Display information of a Compute Engine + instance. + + This field is a member of `oneof`_ ``step_info``. + firewall (google.cloud.network_management_v1.types.FirewallInfo): + Display information of a Compute Engine + firewall rule. + + This field is a member of `oneof`_ ``step_info``. + route (google.cloud.network_management_v1.types.RouteInfo): + Display information of a Compute Engine + route. + + This field is a member of `oneof`_ ``step_info``. + endpoint (google.cloud.network_management_v1.types.EndpointInfo): + Display information of the source and + destination under analysis. The endpoint + information in an intermediate state may differ + with the initial input, as it might be modified + by state like NAT, or Connection Proxy. + + This field is a member of `oneof`_ ``step_info``. + google_service (google.cloud.network_management_v1.types.GoogleServiceInfo): + Display information of a Google service + + This field is a member of `oneof`_ ``step_info``. + forwarding_rule (google.cloud.network_management_v1.types.ForwardingRuleInfo): + Display information of a Compute Engine + forwarding rule. + + This field is a member of `oneof`_ ``step_info``. + vpn_gateway (google.cloud.network_management_v1.types.VpnGatewayInfo): + Display information of a Compute Engine VPN + gateway. + + This field is a member of `oneof`_ ``step_info``. + vpn_tunnel (google.cloud.network_management_v1.types.VpnTunnelInfo): + Display information of a Compute Engine VPN + tunnel. + + This field is a member of `oneof`_ ``step_info``. + vpc_connector (google.cloud.network_management_v1.types.VpcConnectorInfo): + Display information of a VPC connector. + + This field is a member of `oneof`_ ``step_info``. + deliver (google.cloud.network_management_v1.types.DeliverInfo): + Display information of the final state + "deliver" and reason. + + This field is a member of `oneof`_ ``step_info``. + forward (google.cloud.network_management_v1.types.ForwardInfo): + Display information of the final state + "forward" and reason. + + This field is a member of `oneof`_ ``step_info``. + abort (google.cloud.network_management_v1.types.AbortInfo): + Display information of the final state + "abort" and reason. + + This field is a member of `oneof`_ ``step_info``. + drop (google.cloud.network_management_v1.types.DropInfo): + Display information of the final state "drop" + and reason. + + This field is a member of `oneof`_ ``step_info``. + load_balancer (google.cloud.network_management_v1.types.LoadBalancerInfo): + Display information of the load balancers. Deprecated in + favor of the ``load_balancer_backend_info`` field, not used + in new tests. + + This field is a member of `oneof`_ ``step_info``. + network (google.cloud.network_management_v1.types.NetworkInfo): + Display information of a Google Cloud + network. + + This field is a member of `oneof`_ ``step_info``. + gke_master (google.cloud.network_management_v1.types.GKEMasterInfo): + Display information of a Google Kubernetes + Engine cluster master. + + This field is a member of `oneof`_ ``step_info``. + cloud_sql_instance (google.cloud.network_management_v1.types.CloudSQLInstanceInfo): + Display information of a Cloud SQL instance. + + This field is a member of `oneof`_ ``step_info``. + redis_instance (google.cloud.network_management_v1.types.RedisInstanceInfo): + Display information of a Redis Instance. + + This field is a member of `oneof`_ ``step_info``. + redis_cluster (google.cloud.network_management_v1.types.RedisClusterInfo): + Display information of a Redis Cluster. + + This field is a member of `oneof`_ ``step_info``. + cloud_function (google.cloud.network_management_v1.types.CloudFunctionInfo): + Display information of a Cloud Function. + + This field is a member of `oneof`_ ``step_info``. + app_engine_version (google.cloud.network_management_v1.types.AppEngineVersionInfo): + Display information of an App Engine service + version. + + This field is a member of `oneof`_ ``step_info``. + cloud_run_revision (google.cloud.network_management_v1.types.CloudRunRevisionInfo): + Display information of a Cloud Run revision. + + This field is a member of `oneof`_ ``step_info``. + nat (google.cloud.network_management_v1.types.NatInfo): + Display information of a NAT. + + This field is a member of `oneof`_ ``step_info``. + proxy_connection (google.cloud.network_management_v1.types.ProxyConnectionInfo): + Display information of a ProxyConnection. + + This field is a member of `oneof`_ ``step_info``. + load_balancer_backend_info (google.cloud.network_management_v1.types.LoadBalancerBackendInfo): + Display information of a specific load + balancer backend. + + This field is a member of `oneof`_ ``step_info``. + storage_bucket (google.cloud.network_management_v1.types.StorageBucketInfo): + Display information of a Storage Bucket. Used + only for return traces. + + This field is a member of `oneof`_ ``step_info``. + serverless_neg (google.cloud.network_management_v1.types.ServerlessNegInfo): + Display information of a Serverless network + endpoint group backend. Used only for return + traces. + + This field is a member of `oneof`_ ``step_info``. + """ + class State(proto.Enum): + r"""Type of states that are defined in the network state machine. + Each step in the packet trace is in a specific state. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + START_FROM_INSTANCE (1): + Initial state: packet originating from a + Compute Engine instance. An InstanceInfo is + populated with starting instance information. + START_FROM_INTERNET (2): + Initial state: packet originating from the + internet. The endpoint information is populated. + START_FROM_GOOGLE_SERVICE (27): + Initial state: packet originating from a Google service. The + google_service information is populated. + START_FROM_PRIVATE_NETWORK (3): + Initial state: packet originating from a VPC + or on-premises network with internal source IP. + If the source is a VPC network visible to the + user, a NetworkInfo is populated with details of + the network. + START_FROM_GKE_MASTER (21): + Initial state: packet originating from a + Google Kubernetes Engine cluster master. A + GKEMasterInfo is populated with starting + instance information. + START_FROM_CLOUD_SQL_INSTANCE (22): + Initial state: packet originating from a + Cloud SQL instance. A CloudSQLInstanceInfo is + populated with starting instance information. + START_FROM_REDIS_INSTANCE (32): + Initial state: packet originating from a + Redis instance. A RedisInstanceInfo is populated + with starting instance information. + START_FROM_REDIS_CLUSTER (33): + Initial state: packet originating from a + Redis Cluster. A RedisClusterInfo is populated + with starting Cluster information. + START_FROM_CLOUD_FUNCTION (23): + Initial state: packet originating from a + Cloud Function. A CloudFunctionInfo is populated + with starting function information. + START_FROM_APP_ENGINE_VERSION (25): + Initial state: packet originating from an App + Engine service version. An AppEngineVersionInfo + is populated with starting version information. + START_FROM_CLOUD_RUN_REVISION (26): + Initial state: packet originating from a + Cloud Run revision. A CloudRunRevisionInfo is + populated with starting revision information. + START_FROM_STORAGE_BUCKET (29): + Initial state: packet originating from a Storage Bucket. + Used only for return traces. The storage_bucket information + is populated. + START_FROM_PSC_PUBLISHED_SERVICE (30): + Initial state: packet originating from a + published service that uses Private Service + Connect. Used only for return traces. + START_FROM_SERVERLESS_NEG (31): + Initial state: packet originating from a serverless network + endpoint group backend. Used only for return traces. The + serverless_neg information is populated. + APPLY_INGRESS_FIREWALL_RULE (4): + Config checking state: verify ingress + firewall rule. + APPLY_EGRESS_FIREWALL_RULE (5): + Config checking state: verify egress firewall + rule. + APPLY_ROUTE (6): + Config checking state: verify route. + APPLY_FORWARDING_RULE (7): + Config checking state: match forwarding rule. + ANALYZE_LOAD_BALANCER_BACKEND (28): + Config checking state: verify load balancer + backend configuration. + SPOOFING_APPROVED (8): + Config checking state: packet sent or + received under foreign IP address and allowed. + ARRIVE_AT_INSTANCE (9): + Forwarding state: arriving at a Compute + Engine instance. + ARRIVE_AT_INTERNAL_LOAD_BALANCER (10): + Forwarding state: arriving at a Compute + Engine internal load balancer. + ARRIVE_AT_EXTERNAL_LOAD_BALANCER (11): + Forwarding state: arriving at a Compute + Engine external load balancer. + ARRIVE_AT_VPN_GATEWAY (12): + Forwarding state: arriving at a Cloud VPN + gateway. + ARRIVE_AT_VPN_TUNNEL (13): + Forwarding state: arriving at a Cloud VPN + tunnel. + ARRIVE_AT_VPC_CONNECTOR (24): + Forwarding state: arriving at a VPC + connector. + NAT (14): + Transition state: packet header translated. + PROXY_CONNECTION (15): + Transition state: original connection is + terminated and a new proxied connection is + initiated. + DELIVER (16): + Final state: packet could be delivered. + DROP (17): + Final state: packet could be dropped. + FORWARD (18): + Final state: packet could be forwarded to a + network with an unknown configuration. + ABORT (19): + Final state: analysis is aborted. + VIEWER_PERMISSION_MISSING (20): + Special state: viewer of the test result does + not have permission to see the configuration in + this step. + """ + STATE_UNSPECIFIED = 0 + START_FROM_INSTANCE = 1 + START_FROM_INTERNET = 2 + START_FROM_GOOGLE_SERVICE = 27 + START_FROM_PRIVATE_NETWORK = 3 + START_FROM_GKE_MASTER = 21 + START_FROM_CLOUD_SQL_INSTANCE = 22 + START_FROM_REDIS_INSTANCE = 32 + START_FROM_REDIS_CLUSTER = 33 + START_FROM_CLOUD_FUNCTION = 23 + START_FROM_APP_ENGINE_VERSION = 25 + START_FROM_CLOUD_RUN_REVISION = 26 + START_FROM_STORAGE_BUCKET = 29 + START_FROM_PSC_PUBLISHED_SERVICE = 30 + START_FROM_SERVERLESS_NEG = 31 + APPLY_INGRESS_FIREWALL_RULE = 4 + APPLY_EGRESS_FIREWALL_RULE = 5 + APPLY_ROUTE = 6 + APPLY_FORWARDING_RULE = 7 + ANALYZE_LOAD_BALANCER_BACKEND = 28 + SPOOFING_APPROVED = 8 + ARRIVE_AT_INSTANCE = 9 + ARRIVE_AT_INTERNAL_LOAD_BALANCER = 10 + ARRIVE_AT_EXTERNAL_LOAD_BALANCER = 11 + ARRIVE_AT_VPN_GATEWAY = 12 + ARRIVE_AT_VPN_TUNNEL = 13 + ARRIVE_AT_VPC_CONNECTOR = 24 + NAT = 14 + PROXY_CONNECTION = 15 + DELIVER = 16 + DROP = 17 + FORWARD = 18 + ABORT = 19 + VIEWER_PERMISSION_MISSING = 20 + + description: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + causes_drop: bool = proto.Field( + proto.BOOL, + number=3, + ) + project_id: str = proto.Field( + proto.STRING, + number=4, + ) + instance: 'InstanceInfo' = proto.Field( + proto.MESSAGE, + number=5, + oneof='step_info', + message='InstanceInfo', + ) + firewall: 'FirewallInfo' = proto.Field( + proto.MESSAGE, + number=6, + oneof='step_info', + message='FirewallInfo', + ) + route: 'RouteInfo' = proto.Field( + proto.MESSAGE, + number=7, + oneof='step_info', + message='RouteInfo', + ) + endpoint: 'EndpointInfo' = proto.Field( + proto.MESSAGE, + number=8, + oneof='step_info', + message='EndpointInfo', + ) + google_service: 'GoogleServiceInfo' = proto.Field( + proto.MESSAGE, + number=24, + oneof='step_info', + message='GoogleServiceInfo', + ) + forwarding_rule: 'ForwardingRuleInfo' = proto.Field( + proto.MESSAGE, + number=9, + oneof='step_info', + message='ForwardingRuleInfo', + ) + vpn_gateway: 'VpnGatewayInfo' = proto.Field( + proto.MESSAGE, + number=10, + oneof='step_info', + message='VpnGatewayInfo', + ) + vpn_tunnel: 'VpnTunnelInfo' = proto.Field( + proto.MESSAGE, + number=11, + oneof='step_info', + message='VpnTunnelInfo', + ) + vpc_connector: 'VpcConnectorInfo' = proto.Field( + proto.MESSAGE, + number=21, + oneof='step_info', + message='VpcConnectorInfo', + ) + deliver: 'DeliverInfo' = proto.Field( + proto.MESSAGE, + number=12, + oneof='step_info', + message='DeliverInfo', + ) + forward: 'ForwardInfo' = proto.Field( + proto.MESSAGE, + number=13, + oneof='step_info', + message='ForwardInfo', + ) + abort: 'AbortInfo' = proto.Field( + proto.MESSAGE, + number=14, + oneof='step_info', + message='AbortInfo', + ) + drop: 'DropInfo' = proto.Field( + proto.MESSAGE, + number=15, + oneof='step_info', + message='DropInfo', + ) + load_balancer: 'LoadBalancerInfo' = proto.Field( + proto.MESSAGE, + number=16, + oneof='step_info', + message='LoadBalancerInfo', + ) + network: 'NetworkInfo' = proto.Field( + proto.MESSAGE, + number=17, + oneof='step_info', + message='NetworkInfo', + ) + gke_master: 'GKEMasterInfo' = proto.Field( + proto.MESSAGE, + number=18, + oneof='step_info', + message='GKEMasterInfo', + ) + cloud_sql_instance: 'CloudSQLInstanceInfo' = proto.Field( + proto.MESSAGE, + number=19, + oneof='step_info', + message='CloudSQLInstanceInfo', + ) + redis_instance: 'RedisInstanceInfo' = proto.Field( + proto.MESSAGE, + number=30, + oneof='step_info', + message='RedisInstanceInfo', + ) + redis_cluster: 'RedisClusterInfo' = proto.Field( + proto.MESSAGE, + number=31, + oneof='step_info', + message='RedisClusterInfo', + ) + cloud_function: 'CloudFunctionInfo' = proto.Field( + proto.MESSAGE, + number=20, + oneof='step_info', + message='CloudFunctionInfo', + ) + app_engine_version: 'AppEngineVersionInfo' = proto.Field( + proto.MESSAGE, + number=22, + oneof='step_info', + message='AppEngineVersionInfo', + ) + cloud_run_revision: 'CloudRunRevisionInfo' = proto.Field( + proto.MESSAGE, + number=23, + oneof='step_info', + message='CloudRunRevisionInfo', + ) + nat: 'NatInfo' = proto.Field( + proto.MESSAGE, + number=25, + oneof='step_info', + message='NatInfo', + ) + proxy_connection: 'ProxyConnectionInfo' = proto.Field( + proto.MESSAGE, + number=26, + oneof='step_info', + message='ProxyConnectionInfo', + ) + load_balancer_backend_info: 'LoadBalancerBackendInfo' = proto.Field( + proto.MESSAGE, + number=27, + oneof='step_info', + message='LoadBalancerBackendInfo', + ) + storage_bucket: 'StorageBucketInfo' = proto.Field( + proto.MESSAGE, + number=28, + oneof='step_info', + message='StorageBucketInfo', + ) + serverless_neg: 'ServerlessNegInfo' = proto.Field( + proto.MESSAGE, + number=29, + oneof='step_info', + message='ServerlessNegInfo', + ) + + +class InstanceInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + instance. + + Attributes: + display_name (str): + Name of a Compute Engine instance. + uri (str): + URI of a Compute Engine instance. + interface (str): + Name of the network interface of a Compute + Engine instance. + network_uri (str): + URI of a Compute Engine network. + internal_ip (str): + Internal IP address of the network interface. + external_ip (str): + External IP address of the network interface. + network_tags (MutableSequence[str]): + Network tags configured on the instance. + service_account (str): + Service account authorized for the instance. + psc_network_attachment_uri (str): + URI of the PSC network attachment the NIC is + attached to (if relevant). + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + interface: str = proto.Field( + proto.STRING, + number=3, + ) + network_uri: str = proto.Field( + proto.STRING, + number=4, + ) + internal_ip: str = proto.Field( + proto.STRING, + number=5, + ) + external_ip: str = proto.Field( + proto.STRING, + number=6, + ) + network_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + service_account: str = proto.Field( + proto.STRING, + number=8, + ) + psc_network_attachment_uri: str = proto.Field( + proto.STRING, + number=9, + ) + + +class NetworkInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + network. Next ID: 7 + + Attributes: + display_name (str): + Name of a Compute Engine network. + uri (str): + URI of a Compute Engine network. + matched_subnet_uri (str): + URI of the subnet matching the source IP + address of the test. + matched_ip_range (str): + The IP range of the subnet matching the + source IP address of the test. + region (str): + The region of the subnet matching the source + IP address of the test. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + matched_subnet_uri: str = proto.Field( + proto.STRING, + number=5, + ) + matched_ip_range: str = proto.Field( + proto.STRING, + number=4, + ) + region: str = proto.Field( + proto.STRING, + number=6, + ) + + +class FirewallInfo(proto.Message): + r"""For display only. Metadata associated with a VPC firewall + rule, an implied VPC firewall rule, or a firewall policy rule. + + Attributes: + display_name (str): + The display name of the firewall rule. This + field might be empty for firewall policy rules. + uri (str): + The URI of the firewall rule. This field is + not applicable to implied VPC firewall rules. + direction (str): + Possible values: INGRESS, EGRESS + action (str): + Possible values: ALLOW, DENY, APPLY_SECURITY_PROFILE_GROUP + priority (int): + The priority of the firewall rule. + network_uri (str): + The URI of the VPC network that the firewall + rule is associated with. This field is not + applicable to hierarchical firewall policy + rules. + target_tags (MutableSequence[str]): + The target tags defined by the VPC firewall + rule. This field is not applicable to firewall + policy rules. + target_service_accounts (MutableSequence[str]): + The target service accounts specified by the + firewall rule. + policy (str): + The name of the firewall policy that this + rule is associated with. This field is not + applicable to VPC firewall rules and implied VPC + firewall rules. + policy_uri (str): + The URI of the firewall policy that this rule + is associated with. This field is not applicable + to VPC firewall rules and implied VPC firewall + rules. + firewall_rule_type (google.cloud.network_management_v1.types.FirewallInfo.FirewallRuleType): + The firewall rule's type. + """ + class FirewallRuleType(proto.Enum): + r"""The firewall rule's type. + + Values: + FIREWALL_RULE_TYPE_UNSPECIFIED (0): + Unspecified type. + HIERARCHICAL_FIREWALL_POLICY_RULE (1): + Hierarchical firewall policy rule. For details, see + `Hierarchical firewall policies + overview `__. + VPC_FIREWALL_RULE (2): + VPC firewall rule. For details, see `VPC firewall rules + overview `__. + IMPLIED_VPC_FIREWALL_RULE (3): + Implied VPC firewall rule. For details, see `Implied + rules `__. + SERVERLESS_VPC_ACCESS_MANAGED_FIREWALL_RULE (4): + Implicit firewall rules that are managed by serverless VPC + access to allow ingress access. They are not visible in the + Google Cloud console. For details, see `VPC connector's + implicit + rules `__. + NETWORK_FIREWALL_POLICY_RULE (5): + Global network firewall policy rule. For details, see + `Network firewall + policies `__. + NETWORK_REGIONAL_FIREWALL_POLICY_RULE (6): + Regional network firewall policy rule. For details, see + `Regional network firewall + policies `__. + UNSUPPORTED_FIREWALL_POLICY_RULE (100): + Firewall policy rule containing attributes not yet supported + in Connectivity tests. Firewall analysis is skipped if such + a rule can potentially be matched. Please see the `list of + unsupported + configurations `__. + TRACKING_STATE (101): + Tracking state for response traffic created when request + traffic goes through allow firewall rule. For details, see + `firewall rules + specifications `__ + """ + FIREWALL_RULE_TYPE_UNSPECIFIED = 0 + HIERARCHICAL_FIREWALL_POLICY_RULE = 1 + VPC_FIREWALL_RULE = 2 + IMPLIED_VPC_FIREWALL_RULE = 3 + SERVERLESS_VPC_ACCESS_MANAGED_FIREWALL_RULE = 4 + NETWORK_FIREWALL_POLICY_RULE = 5 + NETWORK_REGIONAL_FIREWALL_POLICY_RULE = 6 + UNSUPPORTED_FIREWALL_POLICY_RULE = 100 + TRACKING_STATE = 101 + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + direction: str = proto.Field( + proto.STRING, + number=3, + ) + action: str = proto.Field( + proto.STRING, + number=4, + ) + priority: int = proto.Field( + proto.INT32, + number=5, + ) + network_uri: str = proto.Field( + proto.STRING, + number=6, + ) + target_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + target_service_accounts: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + policy: str = proto.Field( + proto.STRING, + number=9, + ) + policy_uri: str = proto.Field( + proto.STRING, + number=11, + ) + firewall_rule_type: FirewallRuleType = proto.Field( + proto.ENUM, + number=10, + enum=FirewallRuleType, + ) + + +class RouteInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + route. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + route_type (google.cloud.network_management_v1.types.RouteInfo.RouteType): + Type of route. + next_hop_type (google.cloud.network_management_v1.types.RouteInfo.NextHopType): + Type of next hop. + route_scope (google.cloud.network_management_v1.types.RouteInfo.RouteScope): + Indicates where route is applicable. + display_name (str): + Name of a route. + uri (str): + URI of a route (if applicable). + region (str): + Region of the route (if applicable). + dest_ip_range (str): + Destination IP range of the route. + next_hop (str): + Next hop of the route. + network_uri (str): + URI of a Compute Engine network. NETWORK + routes only. + priority (int): + Priority of the route. + instance_tags (MutableSequence[str]): + Instance tags of the route. + src_ip_range (str): + Source IP address range of the route. Policy + based routes only. + dest_port_ranges (MutableSequence[str]): + Destination port ranges of the route. Policy + based routes only. + src_port_ranges (MutableSequence[str]): + Source port ranges of the route. Policy based + routes only. + protocols (MutableSequence[str]): + Protocols of the route. Policy based routes + only. + ncc_hub_uri (str): + URI of a NCC Hub. NCC_HUB routes only. + + This field is a member of `oneof`_ ``_ncc_hub_uri``. + ncc_spoke_uri (str): + URI of a NCC Spoke. NCC_HUB routes only. + + This field is a member of `oneof`_ ``_ncc_spoke_uri``. + advertised_route_source_router_uri (str): + For advertised dynamic routes, the URI of the + Cloud Router that advertised the corresponding + IP prefix. + + This field is a member of `oneof`_ ``_advertised_route_source_router_uri``. + advertised_route_next_hop_uri (str): + For advertised routes, the URI of their next + hop, i.e. the URI of the hybrid endpoint (VPN + tunnel, Interconnect attachment, NCC router + appliance) the advertised prefix is advertised + through, or URI of the source peered network. + + This field is a member of `oneof`_ ``_advertised_route_next_hop_uri``. + """ + class RouteType(proto.Enum): + r"""Type of route: + + Values: + ROUTE_TYPE_UNSPECIFIED (0): + Unspecified type. Default value. + SUBNET (1): + Route is a subnet route automatically created + by the system. + STATIC (2): + Static route created by the user, including + the default route to the internet. + DYNAMIC (3): + Dynamic route exchanged between BGP peers. + PEERING_SUBNET (4): + A subnet route received from peering network. + PEERING_STATIC (5): + A static route received from peering network. + PEERING_DYNAMIC (6): + A dynamic route received from peering + network. + POLICY_BASED (7): + Policy based route. + ADVERTISED (101): + Advertised route. Synthetic route which is + used to transition from the + StartFromPrivateNetwork state in Connectivity + tests. + """ + ROUTE_TYPE_UNSPECIFIED = 0 + SUBNET = 1 + STATIC = 2 + DYNAMIC = 3 + PEERING_SUBNET = 4 + PEERING_STATIC = 5 + PEERING_DYNAMIC = 6 + POLICY_BASED = 7 + ADVERTISED = 101 + + class NextHopType(proto.Enum): + r"""Type of next hop: + + Values: + NEXT_HOP_TYPE_UNSPECIFIED (0): + Unspecified type. Default value. + NEXT_HOP_IP (1): + Next hop is an IP address. + NEXT_HOP_INSTANCE (2): + Next hop is a Compute Engine instance. + NEXT_HOP_NETWORK (3): + Next hop is a VPC network gateway. + NEXT_HOP_PEERING (4): + Next hop is a peering VPC. + NEXT_HOP_INTERCONNECT (5): + Next hop is an interconnect. + NEXT_HOP_VPN_TUNNEL (6): + Next hop is a VPN tunnel. + NEXT_HOP_VPN_GATEWAY (7): + Next hop is a VPN gateway. This scenario only + happens when tracing connectivity from an + on-premises network to Google Cloud through a + VPN. The analysis simulates a packet departing + from the on-premises network through a VPN + tunnel and arriving at a Cloud VPN gateway. + NEXT_HOP_INTERNET_GATEWAY (8): + Next hop is an internet gateway. + NEXT_HOP_BLACKHOLE (9): + Next hop is blackhole; that is, the next hop + either does not exist or is not running. + NEXT_HOP_ILB (10): + Next hop is the forwarding rule of an + Internal Load Balancer. + NEXT_HOP_ROUTER_APPLIANCE (11): + Next hop is a `router appliance + instance `__. + NEXT_HOP_NCC_HUB (12): + Next hop is an NCC hub. + """ + NEXT_HOP_TYPE_UNSPECIFIED = 0 + NEXT_HOP_IP = 1 + NEXT_HOP_INSTANCE = 2 + NEXT_HOP_NETWORK = 3 + NEXT_HOP_PEERING = 4 + NEXT_HOP_INTERCONNECT = 5 + NEXT_HOP_VPN_TUNNEL = 6 + NEXT_HOP_VPN_GATEWAY = 7 + NEXT_HOP_INTERNET_GATEWAY = 8 + NEXT_HOP_BLACKHOLE = 9 + NEXT_HOP_ILB = 10 + NEXT_HOP_ROUTER_APPLIANCE = 11 + NEXT_HOP_NCC_HUB = 12 + + class RouteScope(proto.Enum): + r"""Indicates where routes are applicable. + + Values: + ROUTE_SCOPE_UNSPECIFIED (0): + Unspecified scope. Default value. + NETWORK (1): + Route is applicable to packets in Network. + NCC_HUB (2): + Route is applicable to packets using NCC + Hub's routing table. + """ + ROUTE_SCOPE_UNSPECIFIED = 0 + NETWORK = 1 + NCC_HUB = 2 + + route_type: RouteType = proto.Field( + proto.ENUM, + number=8, + enum=RouteType, + ) + next_hop_type: NextHopType = proto.Field( + proto.ENUM, + number=9, + enum=NextHopType, + ) + route_scope: RouteScope = proto.Field( + proto.ENUM, + number=14, + enum=RouteScope, + ) + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + region: str = proto.Field( + proto.STRING, + number=19, + ) + dest_ip_range: str = proto.Field( + proto.STRING, + number=3, + ) + next_hop: str = proto.Field( + proto.STRING, + number=4, + ) + network_uri: str = proto.Field( + proto.STRING, + number=5, + ) + priority: int = proto.Field( + proto.INT32, + number=6, + ) + instance_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + src_ip_range: str = proto.Field( + proto.STRING, + number=10, + ) + dest_port_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=11, + ) + src_port_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=12, + ) + protocols: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=13, + ) + ncc_hub_uri: str = proto.Field( + proto.STRING, + number=15, + optional=True, + ) + ncc_spoke_uri: str = proto.Field( + proto.STRING, + number=16, + optional=True, + ) + advertised_route_source_router_uri: str = proto.Field( + proto.STRING, + number=17, + optional=True, + ) + advertised_route_next_hop_uri: str = proto.Field( + proto.STRING, + number=18, + optional=True, + ) + + +class GoogleServiceInfo(proto.Message): + r"""For display only. Details of a Google Service sending packets to a + VPC network. Although the source IP might be a publicly routable + address, some Google Services use special routes within Google + production infrastructure to reach Compute Engine Instances. + https://cloud.google.com/vpc/docs/routes#special_return_paths + + Attributes: + source_ip (str): + Source IP address. + google_service_type (google.cloud.network_management_v1.types.GoogleServiceInfo.GoogleServiceType): + Recognized type of a Google Service. + """ + class GoogleServiceType(proto.Enum): + r"""Recognized type of a Google Service. + + Values: + GOOGLE_SERVICE_TYPE_UNSPECIFIED (0): + Unspecified Google Service. + IAP (1): + Identity aware proxy. + https://cloud.google.com/iap/docs/using-tcp-forwarding + GFE_PROXY_OR_HEALTH_CHECK_PROBER (2): + One of two services sharing IP ranges: + + - Load Balancer proxy + - Centralized Health Check prober + https://cloud.google.com/load-balancing/docs/firewall-rules + CLOUD_DNS (3): + Connectivity from Cloud DNS to forwarding + targets or alternate name servers that use + private routing. + https://cloud.google.com/dns/docs/zones/forwarding-zones#firewall-rules + https://cloud.google.com/dns/docs/policies#firewall-rules + GOOGLE_API (4): + private.googleapis.com and + restricted.googleapis.com + GOOGLE_API_PSC (5): + Google API via Private Service Connect. + https://cloud.google.com/vpc/docs/configure-private-service-connect-apis + GOOGLE_API_VPC_SC (6): + Google API via VPC Service Controls. + https://cloud.google.com/vpc/docs/configure-private-service-connect-apis + """ + GOOGLE_SERVICE_TYPE_UNSPECIFIED = 0 + IAP = 1 + GFE_PROXY_OR_HEALTH_CHECK_PROBER = 2 + CLOUD_DNS = 3 + GOOGLE_API = 4 + GOOGLE_API_PSC = 5 + GOOGLE_API_VPC_SC = 6 + + source_ip: str = proto.Field( + proto.STRING, + number=1, + ) + google_service_type: GoogleServiceType = proto.Field( + proto.ENUM, + number=2, + enum=GoogleServiceType, + ) + + +class ForwardingRuleInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + forwarding rule. + + Attributes: + display_name (str): + Name of the forwarding rule. + uri (str): + URI of the forwarding rule. + matched_protocol (str): + Protocol defined in the forwarding rule that + matches the packet. + matched_port_range (str): + Port range defined in the forwarding rule + that matches the packet. + vip (str): + VIP of the forwarding rule. + target (str): + Target type of the forwarding rule. + network_uri (str): + Network URI. + region (str): + Region of the forwarding rule. Set only for + regional forwarding rules. + load_balancer_name (str): + Name of the load balancer the forwarding rule + belongs to. Empty for forwarding rules not + related to load balancers (like PSC forwarding + rules). + psc_service_attachment_uri (str): + URI of the PSC service attachment this + forwarding rule targets (if applicable). + psc_google_api_target (str): + PSC Google API target this forwarding rule + targets (if applicable). + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + matched_protocol: str = proto.Field( + proto.STRING, + number=3, + ) + matched_port_range: str = proto.Field( + proto.STRING, + number=6, + ) + vip: str = proto.Field( + proto.STRING, + number=4, + ) + target: str = proto.Field( + proto.STRING, + number=5, + ) + network_uri: str = proto.Field( + proto.STRING, + number=7, + ) + region: str = proto.Field( + proto.STRING, + number=8, + ) + load_balancer_name: str = proto.Field( + proto.STRING, + number=9, + ) + psc_service_attachment_uri: str = proto.Field( + proto.STRING, + number=10, + ) + psc_google_api_target: str = proto.Field( + proto.STRING, + number=11, + ) + + +class LoadBalancerInfo(proto.Message): + r"""For display only. Metadata associated with a load balancer. + + Attributes: + load_balancer_type (google.cloud.network_management_v1.types.LoadBalancerInfo.LoadBalancerType): + Type of the load balancer. + health_check_uri (str): + URI of the health check for the load + balancer. Deprecated and no longer populated as + different load balancer backends might have + different health checks. + backends (MutableSequence[google.cloud.network_management_v1.types.LoadBalancerBackend]): + Information for the loadbalancer backends. + backend_type (google.cloud.network_management_v1.types.LoadBalancerInfo.BackendType): + Type of load balancer's backend + configuration. + backend_uri (str): + Backend configuration URI. + """ + class LoadBalancerType(proto.Enum): + r"""The type definition for a load balancer: + + Values: + LOAD_BALANCER_TYPE_UNSPECIFIED (0): + Type is unspecified. + INTERNAL_TCP_UDP (1): + Internal TCP/UDP load balancer. + NETWORK_TCP_UDP (2): + Network TCP/UDP load balancer. + HTTP_PROXY (3): + HTTP(S) proxy load balancer. + TCP_PROXY (4): + TCP proxy load balancer. + SSL_PROXY (5): + SSL proxy load balancer. + """ + LOAD_BALANCER_TYPE_UNSPECIFIED = 0 + INTERNAL_TCP_UDP = 1 + NETWORK_TCP_UDP = 2 + HTTP_PROXY = 3 + TCP_PROXY = 4 + SSL_PROXY = 5 + + class BackendType(proto.Enum): + r"""The type definition for a load balancer backend + configuration: + + Values: + BACKEND_TYPE_UNSPECIFIED (0): + Type is unspecified. + BACKEND_SERVICE (1): + Backend Service as the load balancer's + backend. + TARGET_POOL (2): + Target Pool as the load balancer's backend. + TARGET_INSTANCE (3): + Target Instance as the load balancer's + backend. + """ + BACKEND_TYPE_UNSPECIFIED = 0 + BACKEND_SERVICE = 1 + TARGET_POOL = 2 + TARGET_INSTANCE = 3 + + load_balancer_type: LoadBalancerType = proto.Field( + proto.ENUM, + number=1, + enum=LoadBalancerType, + ) + health_check_uri: str = proto.Field( + proto.STRING, + number=2, + ) + backends: MutableSequence['LoadBalancerBackend'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LoadBalancerBackend', + ) + backend_type: BackendType = proto.Field( + proto.ENUM, + number=4, + enum=BackendType, + ) + backend_uri: str = proto.Field( + proto.STRING, + number=5, + ) + + +class LoadBalancerBackend(proto.Message): + r"""For display only. Metadata associated with a specific load + balancer backend. + + Attributes: + display_name (str): + Name of a Compute Engine instance or network + endpoint. + uri (str): + URI of a Compute Engine instance or network + endpoint. + health_check_firewall_state (google.cloud.network_management_v1.types.LoadBalancerBackend.HealthCheckFirewallState): + State of the health check firewall + configuration. + health_check_allowing_firewall_rules (MutableSequence[str]): + A list of firewall rule URIs allowing probes + from health check IP ranges. + health_check_blocking_firewall_rules (MutableSequence[str]): + A list of firewall rule URIs blocking probes + from health check IP ranges. + """ + class HealthCheckFirewallState(proto.Enum): + r"""State of a health check firewall configuration: + + Values: + HEALTH_CHECK_FIREWALL_STATE_UNSPECIFIED (0): + State is unspecified. Default state if not + populated. + CONFIGURED (1): + There are configured firewall rules to allow + health check probes to the backend. + MISCONFIGURED (2): + There are firewall rules configured to allow + partial health check ranges or block all health + check ranges. If a health check probe is sent + from denied IP ranges, the health check to the + backend will fail. Then, the backend will be + marked unhealthy and will not receive traffic + sent to the load balancer. + """ + HEALTH_CHECK_FIREWALL_STATE_UNSPECIFIED = 0 + CONFIGURED = 1 + MISCONFIGURED = 2 + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + health_check_firewall_state: HealthCheckFirewallState = proto.Field( + proto.ENUM, + number=3, + enum=HealthCheckFirewallState, + ) + health_check_allowing_firewall_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + health_check_blocking_firewall_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class VpnGatewayInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + VPN gateway. + + Attributes: + display_name (str): + Name of a VPN gateway. + uri (str): + URI of a VPN gateway. + network_uri (str): + URI of a Compute Engine network where the VPN + gateway is configured. + ip_address (str): + IP address of the VPN gateway. + vpn_tunnel_uri (str): + A VPN tunnel that is associated with this VPN + gateway. There may be multiple VPN tunnels + configured on a VPN gateway, and only the one + relevant to the test is displayed. + region (str): + Name of a Google Cloud region where this VPN + gateway is configured. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + network_uri: str = proto.Field( + proto.STRING, + number=3, + ) + ip_address: str = proto.Field( + proto.STRING, + number=4, + ) + vpn_tunnel_uri: str = proto.Field( + proto.STRING, + number=5, + ) + region: str = proto.Field( + proto.STRING, + number=6, + ) + + +class VpnTunnelInfo(proto.Message): + r"""For display only. Metadata associated with a Compute Engine + VPN tunnel. + + Attributes: + display_name (str): + Name of a VPN tunnel. + uri (str): + URI of a VPN tunnel. + source_gateway (str): + URI of the VPN gateway at local end of the + tunnel. + remote_gateway (str): + URI of a VPN gateway at remote end of the + tunnel. + remote_gateway_ip (str): + Remote VPN gateway's IP address. + source_gateway_ip (str): + Local VPN gateway's IP address. + network_uri (str): + URI of a Compute Engine network where the VPN + tunnel is configured. + region (str): + Name of a Google Cloud region where this VPN + tunnel is configured. + routing_type (google.cloud.network_management_v1.types.VpnTunnelInfo.RoutingType): + Type of the routing policy. + """ + class RoutingType(proto.Enum): + r"""Types of VPN routing policy. For details, refer to `Networks and + Tunnel + routing `__. + + Values: + ROUTING_TYPE_UNSPECIFIED (0): + Unspecified type. Default value. + ROUTE_BASED (1): + Route based VPN. + POLICY_BASED (2): + Policy based routing. + DYNAMIC (3): + Dynamic (BGP) routing. + """ + ROUTING_TYPE_UNSPECIFIED = 0 + ROUTE_BASED = 1 + POLICY_BASED = 2 + DYNAMIC = 3 + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + source_gateway: str = proto.Field( + proto.STRING, + number=3, + ) + remote_gateway: str = proto.Field( + proto.STRING, + number=4, + ) + remote_gateway_ip: str = proto.Field( + proto.STRING, + number=5, + ) + source_gateway_ip: str = proto.Field( + proto.STRING, + number=6, + ) + network_uri: str = proto.Field( + proto.STRING, + number=7, + ) + region: str = proto.Field( + proto.STRING, + number=8, + ) + routing_type: RoutingType = proto.Field( + proto.ENUM, + number=9, + enum=RoutingType, + ) + + +class EndpointInfo(proto.Message): + r"""For display only. The specification of the endpoints for the + test. EndpointInfo is derived from source and destination + Endpoint and validated by the backend data plane model. + + Attributes: + source_ip (str): + Source IP address. + destination_ip (str): + Destination IP address. + protocol (str): + IP protocol in string format, for example: + "TCP", "UDP", "ICMP". + source_port (int): + Source port. Only valid when protocol is TCP + or UDP. + destination_port (int): + Destination port. Only valid when protocol is + TCP or UDP. + source_network_uri (str): + URI of the network where this packet + originates from. + destination_network_uri (str): + URI of the network where this packet is sent + to. + source_agent_uri (str): + URI of the source telemetry agent this packet + originates from. + """ + + source_ip: str = proto.Field( + proto.STRING, + number=1, + ) + destination_ip: str = proto.Field( + proto.STRING, + number=2, + ) + protocol: str = proto.Field( + proto.STRING, + number=3, + ) + source_port: int = proto.Field( + proto.INT32, + number=4, + ) + destination_port: int = proto.Field( + proto.INT32, + number=5, + ) + source_network_uri: str = proto.Field( + proto.STRING, + number=6, + ) + destination_network_uri: str = proto.Field( + proto.STRING, + number=7, + ) + source_agent_uri: str = proto.Field( + proto.STRING, + number=8, + ) + + +class DeliverInfo(proto.Message): + r"""Details of the final state "deliver" and associated resource. + + Attributes: + target (google.cloud.network_management_v1.types.DeliverInfo.Target): + Target type where the packet is delivered to. + resource_uri (str): + URI of the resource that the packet is + delivered to. + ip_address (str): + IP address of the target (if applicable). + storage_bucket (str): + Name of the Cloud Storage Bucket the packet + is delivered to (if applicable). + psc_google_api_target (str): + PSC Google API target the packet is delivered + to (if applicable). + """ + class Target(proto.Enum): + r"""Deliver target types: + + Values: + TARGET_UNSPECIFIED (0): + Target not specified. + INSTANCE (1): + Target is a Compute Engine instance. + INTERNET (2): + Target is the internet. + GOOGLE_API (3): + Target is a Google API. + GKE_MASTER (4): + Target is a Google Kubernetes Engine cluster + master. + CLOUD_SQL_INSTANCE (5): + Target is a Cloud SQL instance. + PSC_PUBLISHED_SERVICE (6): + Target is a published service that uses `Private Service + Connect `__. + PSC_GOOGLE_API (7): + Target is Google APIs that use `Private Service + Connect `__. + PSC_VPC_SC (8): + Target is a VPC-SC that uses `Private Service + Connect `__. + SERVERLESS_NEG (9): + Target is a serverless network endpoint + group. + STORAGE_BUCKET (10): + Target is a Cloud Storage bucket. + PRIVATE_NETWORK (11): + Target is a private network. Used only for + return traces. + CLOUD_FUNCTION (12): + Target is a Cloud Function. Used only for + return traces. + APP_ENGINE_VERSION (13): + Target is a App Engine service version. Used + only for return traces. + CLOUD_RUN_REVISION (14): + Target is a Cloud Run revision. Used only for + return traces. + GOOGLE_MANAGED_SERVICE (15): + Target is a Google-managed service. Used only + for return traces. + REDIS_INSTANCE (16): + Target is a Redis Instance. + REDIS_CLUSTER (17): + Target is a Redis Cluster. + """ + TARGET_UNSPECIFIED = 0 + INSTANCE = 1 + INTERNET = 2 + GOOGLE_API = 3 + GKE_MASTER = 4 + CLOUD_SQL_INSTANCE = 5 + PSC_PUBLISHED_SERVICE = 6 + PSC_GOOGLE_API = 7 + PSC_VPC_SC = 8 + SERVERLESS_NEG = 9 + STORAGE_BUCKET = 10 + PRIVATE_NETWORK = 11 + CLOUD_FUNCTION = 12 + APP_ENGINE_VERSION = 13 + CLOUD_RUN_REVISION = 14 + GOOGLE_MANAGED_SERVICE = 15 + REDIS_INSTANCE = 16 + REDIS_CLUSTER = 17 + + target: Target = proto.Field( + proto.ENUM, + number=1, + enum=Target, + ) + resource_uri: str = proto.Field( + proto.STRING, + number=2, + ) + ip_address: str = proto.Field( + proto.STRING, + number=3, + ) + storage_bucket: str = proto.Field( + proto.STRING, + number=4, + ) + psc_google_api_target: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ForwardInfo(proto.Message): + r"""Details of the final state "forward" and associated resource. + + Attributes: + target (google.cloud.network_management_v1.types.ForwardInfo.Target): + Target type where this packet is forwarded + to. + resource_uri (str): + URI of the resource that the packet is + forwarded to. + ip_address (str): + IP address of the target (if applicable). + """ + class Target(proto.Enum): + r"""Forward target types. + + Values: + TARGET_UNSPECIFIED (0): + Target not specified. + PEERING_VPC (1): + Forwarded to a VPC peering network. + VPN_GATEWAY (2): + Forwarded to a Cloud VPN gateway. + INTERCONNECT (3): + Forwarded to a Cloud Interconnect connection. + GKE_MASTER (4): + Forwarded to a Google Kubernetes Engine + Container cluster master. + IMPORTED_CUSTOM_ROUTE_NEXT_HOP (5): + Forwarded to the next hop of a custom route + imported from a peering VPC. + CLOUD_SQL_INSTANCE (6): + Forwarded to a Cloud SQL instance. + ANOTHER_PROJECT (7): + Forwarded to a VPC network in another + project. + NCC_HUB (8): + Forwarded to an NCC Hub. + ROUTER_APPLIANCE (9): + Forwarded to a router appliance. + """ + TARGET_UNSPECIFIED = 0 + PEERING_VPC = 1 + VPN_GATEWAY = 2 + INTERCONNECT = 3 + GKE_MASTER = 4 + IMPORTED_CUSTOM_ROUTE_NEXT_HOP = 5 + CLOUD_SQL_INSTANCE = 6 + ANOTHER_PROJECT = 7 + NCC_HUB = 8 + ROUTER_APPLIANCE = 9 + + target: Target = proto.Field( + proto.ENUM, + number=1, + enum=Target, + ) + resource_uri: str = proto.Field( + proto.STRING, + number=2, + ) + ip_address: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AbortInfo(proto.Message): + r"""Details of the final state "abort" and associated resource. + + Attributes: + cause (google.cloud.network_management_v1.types.AbortInfo.Cause): + Causes that the analysis is aborted. + resource_uri (str): + URI of the resource that caused the abort. + ip_address (str): + IP address that caused the abort. + projects_missing_permission (MutableSequence[str]): + List of project IDs the user specified in the request but + lacks access to. In this case, analysis is aborted with the + PERMISSION_DENIED cause. + """ + class Cause(proto.Enum): + r"""Abort cause types: + + Values: + CAUSE_UNSPECIFIED (0): + Cause is unspecified. + UNKNOWN_NETWORK (1): + Aborted due to unknown network. Deprecated, + not used in the new tests. + UNKNOWN_PROJECT (3): + Aborted because no project information can be + derived from the test input. Deprecated, not + used in the new tests. + NO_EXTERNAL_IP (7): + Aborted because traffic is sent from a public + IP to an instance without an external IP. + Deprecated, not used in the new tests. + UNINTENDED_DESTINATION (8): + Aborted because none of the traces matches + destination information specified in the input + test request. Deprecated, not used in the new + tests. + SOURCE_ENDPOINT_NOT_FOUND (11): + Aborted because the source endpoint could not + be found. Deprecated, not used in the new tests. + MISMATCHED_SOURCE_NETWORK (12): + Aborted because the source network does not + match the source endpoint. Deprecated, not used + in the new tests. + DESTINATION_ENDPOINT_NOT_FOUND (13): + Aborted because the destination endpoint + could not be found. Deprecated, not used in the + new tests. + MISMATCHED_DESTINATION_NETWORK (14): + Aborted because the destination network does + not match the destination endpoint. Deprecated, + not used in the new tests. + UNKNOWN_IP (2): + Aborted because no endpoint with the packet's + destination IP address is found. + GOOGLE_MANAGED_SERVICE_UNKNOWN_IP (32): + Aborted because no endpoint with the packet's + destination IP is found in the Google-managed + project. + SOURCE_IP_ADDRESS_NOT_IN_SOURCE_NETWORK (23): + Aborted because the source IP address doesn't + belong to any of the subnets of the source VPC + network. + PERMISSION_DENIED (4): + Aborted because user lacks permission to + access all or part of the network configurations + required to run the test. + PERMISSION_DENIED_NO_CLOUD_NAT_CONFIGS (28): + Aborted because user lacks permission to + access Cloud NAT configs required to run the + test. + PERMISSION_DENIED_NO_NEG_ENDPOINT_CONFIGS (29): + Aborted because user lacks permission to + access Network endpoint group endpoint configs + required to run the test. + PERMISSION_DENIED_NO_CLOUD_ROUTER_CONFIGS (36): + Aborted because user lacks permission to + access Cloud Router configs required to run the + test. + NO_SOURCE_LOCATION (5): + Aborted because no valid source or + destination endpoint is derived from the input + test request. + INVALID_ARGUMENT (6): + Aborted because the source or destination + endpoint specified in the request is invalid. + Some examples: + + - The request might contain malformed resource + URI, project ID, or IP address. + - The request might contain inconsistent + information (for example, the request might + include both the instance and the network, but + the instance might not have a NIC in that + network). + TRACE_TOO_LONG (9): + Aborted because the number of steps in the + trace exceeds a certain limit. It might be + caused by a routing loop. + INTERNAL_ERROR (10): + Aborted due to internal server error. + UNSUPPORTED (15): + Aborted because the test scenario is not + supported. + MISMATCHED_IP_VERSION (16): + Aborted because the source and destination + resources have no common IP version. + GKE_KONNECTIVITY_PROXY_UNSUPPORTED (17): + Aborted because the connection between the + control plane and the node of the source cluster + is initiated by the node and managed by the + Konnectivity proxy. + RESOURCE_CONFIG_NOT_FOUND (18): + Aborted because expected resource + configuration was missing. + VM_INSTANCE_CONFIG_NOT_FOUND (24): + Aborted because expected VM instance + configuration was missing. + NETWORK_CONFIG_NOT_FOUND (25): + Aborted because expected network + configuration was missing. + FIREWALL_CONFIG_NOT_FOUND (26): + Aborted because expected firewall + configuration was missing. + ROUTE_CONFIG_NOT_FOUND (27): + Aborted because expected route configuration + was missing. + GOOGLE_MANAGED_SERVICE_AMBIGUOUS_PSC_ENDPOINT (19): + Aborted because a PSC endpoint selection for + the Google-managed service is ambiguous (several + PSC endpoints satisfy test input). + SOURCE_PSC_CLOUD_SQL_UNSUPPORTED (20): + Aborted because tests with a PSC-based Cloud + SQL instance as a source are not supported. + SOURCE_REDIS_CLUSTER_UNSUPPORTED (34): + Aborted because tests with a Redis Cluster as + a source are not supported. + SOURCE_REDIS_INSTANCE_UNSUPPORTED (35): + Aborted because tests with a Redis Instance + as a source are not supported. + SOURCE_FORWARDING_RULE_UNSUPPORTED (21): + Aborted because tests with a forwarding rule + as a source are not supported. + NON_ROUTABLE_IP_ADDRESS (22): + Aborted because one of the endpoints is a + non-routable IP address (loopback, link-local, + etc). + UNKNOWN_ISSUE_IN_GOOGLE_MANAGED_PROJECT (30): + Aborted due to an unknown issue in the + Google-managed project. + UNSUPPORTED_GOOGLE_MANAGED_PROJECT_CONFIG (31): + Aborted due to an unsupported configuration + of the Google-managed project. + """ + CAUSE_UNSPECIFIED = 0 + UNKNOWN_NETWORK = 1 + UNKNOWN_PROJECT = 3 + NO_EXTERNAL_IP = 7 + UNINTENDED_DESTINATION = 8 + SOURCE_ENDPOINT_NOT_FOUND = 11 + MISMATCHED_SOURCE_NETWORK = 12 + DESTINATION_ENDPOINT_NOT_FOUND = 13 + MISMATCHED_DESTINATION_NETWORK = 14 + UNKNOWN_IP = 2 + GOOGLE_MANAGED_SERVICE_UNKNOWN_IP = 32 + SOURCE_IP_ADDRESS_NOT_IN_SOURCE_NETWORK = 23 + PERMISSION_DENIED = 4 + PERMISSION_DENIED_NO_CLOUD_NAT_CONFIGS = 28 + PERMISSION_DENIED_NO_NEG_ENDPOINT_CONFIGS = 29 + PERMISSION_DENIED_NO_CLOUD_ROUTER_CONFIGS = 36 + NO_SOURCE_LOCATION = 5 + INVALID_ARGUMENT = 6 + TRACE_TOO_LONG = 9 + INTERNAL_ERROR = 10 + UNSUPPORTED = 15 + MISMATCHED_IP_VERSION = 16 + GKE_KONNECTIVITY_PROXY_UNSUPPORTED = 17 + RESOURCE_CONFIG_NOT_FOUND = 18 + VM_INSTANCE_CONFIG_NOT_FOUND = 24 + NETWORK_CONFIG_NOT_FOUND = 25 + FIREWALL_CONFIG_NOT_FOUND = 26 + ROUTE_CONFIG_NOT_FOUND = 27 + GOOGLE_MANAGED_SERVICE_AMBIGUOUS_PSC_ENDPOINT = 19 + SOURCE_PSC_CLOUD_SQL_UNSUPPORTED = 20 + SOURCE_REDIS_CLUSTER_UNSUPPORTED = 34 + SOURCE_REDIS_INSTANCE_UNSUPPORTED = 35 + SOURCE_FORWARDING_RULE_UNSUPPORTED = 21 + NON_ROUTABLE_IP_ADDRESS = 22 + UNKNOWN_ISSUE_IN_GOOGLE_MANAGED_PROJECT = 30 + UNSUPPORTED_GOOGLE_MANAGED_PROJECT_CONFIG = 31 + + cause: Cause = proto.Field( + proto.ENUM, + number=1, + enum=Cause, + ) + resource_uri: str = proto.Field( + proto.STRING, + number=2, + ) + ip_address: str = proto.Field( + proto.STRING, + number=4, + ) + projects_missing_permission: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DropInfo(proto.Message): + r"""Details of the final state "drop" and associated resource. + + Attributes: + cause (google.cloud.network_management_v1.types.DropInfo.Cause): + Cause that the packet is dropped. + resource_uri (str): + URI of the resource that caused the drop. + source_ip (str): + Source IP address of the dropped packet (if + relevant). + destination_ip (str): + Destination IP address of the dropped packet + (if relevant). + region (str): + Region of the dropped packet (if relevant). + """ + class Cause(proto.Enum): + r"""Drop cause types: + + Values: + CAUSE_UNSPECIFIED (0): + Cause is unspecified. + UNKNOWN_EXTERNAL_ADDRESS (1): + Destination external address cannot be + resolved to a known target. If the address is + used in a Google Cloud project, provide the + project ID as test input. + FOREIGN_IP_DISALLOWED (2): + A Compute Engine instance can only send or receive a packet + with a foreign IP address if ip_forward is enabled. + FIREWALL_RULE (3): + Dropped due to a firewall rule, unless + allowed due to connection tracking. + NO_ROUTE (4): + Dropped due to no matching routes. + ROUTE_BLACKHOLE (5): + Dropped due to invalid route. Route's next + hop is a blackhole. + ROUTE_WRONG_NETWORK (6): + Packet is sent to a wrong (unintended) + network. Example: you trace a packet from + VM1:Network1 to VM2:Network2, however, the route + configured in Network1 sends the packet destined + for VM2's IP address to Network3. + ROUTE_NEXT_HOP_IP_ADDRESS_NOT_RESOLVED (42): + Route's next hop IP address cannot be + resolved to a GCP resource. + ROUTE_NEXT_HOP_RESOURCE_NOT_FOUND (43): + Route's next hop resource is not found. + ROUTE_NEXT_HOP_INSTANCE_WRONG_NETWORK (49): + Route's next hop instance doesn't have a NIC + in the route's network. + ROUTE_NEXT_HOP_INSTANCE_NON_PRIMARY_IP (50): + Route's next hop IP address is not a primary + IP address of the next hop instance. + ROUTE_NEXT_HOP_FORWARDING_RULE_IP_MISMATCH (51): + Route's next hop forwarding rule doesn't + match next hop IP address. + ROUTE_NEXT_HOP_VPN_TUNNEL_NOT_ESTABLISHED (52): + Route's next hop VPN tunnel is down (does not + have valid IKE SAs). + ROUTE_NEXT_HOP_FORWARDING_RULE_TYPE_INVALID (53): + Route's next hop forwarding rule type is + invalid (it's not a forwarding rule of the + internal passthrough load balancer). + NO_ROUTE_FROM_INTERNET_TO_PRIVATE_IPV6_ADDRESS (44): + Packet is sent from the Internet to the + private IPv6 address. + VPN_TUNNEL_LOCAL_SELECTOR_MISMATCH (45): + The packet does not match a policy-based VPN + tunnel local selector. + VPN_TUNNEL_REMOTE_SELECTOR_MISMATCH (46): + The packet does not match a policy-based VPN + tunnel remote selector. + PRIVATE_TRAFFIC_TO_INTERNET (7): + Packet with internal destination address sent + to the internet gateway. + PRIVATE_GOOGLE_ACCESS_DISALLOWED (8): + Instance with only an internal IP address + tries to access Google API and services, but + private Google access is not enabled in the + subnet. + PRIVATE_GOOGLE_ACCESS_VIA_VPN_TUNNEL_UNSUPPORTED (47): + Source endpoint tries to access Google API + and services through the VPN tunnel to another + network, but Private Google Access needs to be + enabled in the source endpoint network. + NO_EXTERNAL_ADDRESS (9): + Instance with only an internal IP address + tries to access external hosts, but Cloud NAT is + not enabled in the subnet, unless special + configurations on a VM allow this connection. + UNKNOWN_INTERNAL_ADDRESS (10): + Destination internal address cannot be + resolved to a known target. If this is a shared + VPC scenario, verify if the service project ID + is provided as test input. Otherwise, verify if + the IP address is being used in the project. + FORWARDING_RULE_MISMATCH (11): + Forwarding rule's protocol and ports do not + match the packet header. + FORWARDING_RULE_NO_INSTANCES (12): + Forwarding rule does not have backends + configured. + FIREWALL_BLOCKING_LOAD_BALANCER_BACKEND_HEALTH_CHECK (13): + Firewalls block the health check probes to the backends and + cause the backends to be unavailable for traffic from the + load balancer. For more details, see `Health check firewall + rules `__. + INSTANCE_NOT_RUNNING (14): + Packet is sent from or to a Compute Engine + instance that is not in a running state. + GKE_CLUSTER_NOT_RUNNING (27): + Packet sent from or to a GKE cluster that is + not in running state. + CLOUD_SQL_INSTANCE_NOT_RUNNING (28): + Packet sent from or to a Cloud SQL instance + that is not in running state. + REDIS_INSTANCE_NOT_RUNNING (68): + Packet sent from or to a Redis Instance that + is not in running state. + REDIS_CLUSTER_NOT_RUNNING (69): + Packet sent from or to a Redis Cluster that + is not in running state. + TRAFFIC_TYPE_BLOCKED (15): + The type of traffic is blocked and the user cannot configure + a firewall rule to enable it. See `Always blocked + traffic `__ + for more details. + GKE_MASTER_UNAUTHORIZED_ACCESS (16): + Access to Google Kubernetes Engine cluster master's endpoint + is not authorized. See `Access to the cluster + endpoints `__ + for more details. + CLOUD_SQL_INSTANCE_UNAUTHORIZED_ACCESS (17): + Access to the Cloud SQL instance endpoint is not authorized. + See `Authorizing with authorized + networks `__ + for more details. + DROPPED_INSIDE_GKE_SERVICE (18): + Packet was dropped inside Google Kubernetes + Engine Service. + DROPPED_INSIDE_CLOUD_SQL_SERVICE (19): + Packet was dropped inside Cloud SQL Service. + GOOGLE_MANAGED_SERVICE_NO_PEERING (20): + Packet was dropped because there is no + peering between the originating network and the + Google Managed Services Network. + GOOGLE_MANAGED_SERVICE_NO_PSC_ENDPOINT (38): + Packet was dropped because the Google-managed + service uses Private Service Connect (PSC), but + the PSC endpoint is not found in the project. + GKE_PSC_ENDPOINT_MISSING (36): + Packet was dropped because the GKE cluster + uses Private Service Connect (PSC), but the PSC + endpoint is not found in the project. + CLOUD_SQL_INSTANCE_NO_IP_ADDRESS (21): + Packet was dropped because the Cloud SQL + instance has neither a private nor a public IP + address. + GKE_CONTROL_PLANE_REGION_MISMATCH (30): + Packet was dropped because a GKE cluster + private endpoint is unreachable from a region + different from the cluster's region. + PUBLIC_GKE_CONTROL_PLANE_TO_PRIVATE_DESTINATION (31): + Packet sent from a public GKE cluster control + plane to a private IP address. + GKE_CONTROL_PLANE_NO_ROUTE (32): + Packet was dropped because there is no route + from a GKE cluster control plane to a + destination network. + CLOUD_SQL_INSTANCE_NOT_CONFIGURED_FOR_EXTERNAL_TRAFFIC (33): + Packet sent from a Cloud SQL instance to an + external IP address is not allowed. The Cloud + SQL instance is not configured to send packets + to external IP addresses. + PUBLIC_CLOUD_SQL_INSTANCE_TO_PRIVATE_DESTINATION (34): + Packet sent from a Cloud SQL instance with + only a public IP address to a private IP + address. + CLOUD_SQL_INSTANCE_NO_ROUTE (35): + Packet was dropped because there is no route + from a Cloud SQL instance to a destination + network. + CLOUD_SQL_CONNECTOR_REQUIRED (63): + Packet was dropped because the Cloud SQL + instance requires all connections to use Cloud + SQL connectors and to target the Cloud SQL proxy + port (3307). + CLOUD_FUNCTION_NOT_ACTIVE (22): + Packet could be dropped because the Cloud + Function is not in an active status. + VPC_CONNECTOR_NOT_SET (23): + Packet could be dropped because no VPC + connector is set. + VPC_CONNECTOR_NOT_RUNNING (24): + Packet could be dropped because the VPC + connector is not in a running state. + VPC_CONNECTOR_SERVERLESS_TRAFFIC_BLOCKED (60): + Packet could be dropped because the traffic + from the serverless service to the VPC connector + is not allowed. + VPC_CONNECTOR_HEALTH_CHECK_TRAFFIC_BLOCKED (61): + Packet could be dropped because the health + check traffic to the VPC connector is not + allowed. + FORWARDING_RULE_REGION_MISMATCH (25): + Packet could be dropped because it was sent + from a different region to a regional forwarding + without global access. + PSC_CONNECTION_NOT_ACCEPTED (26): + The Private Service Connect endpoint is in a + project that is not approved to connect to the + service. + PSC_ENDPOINT_ACCESSED_FROM_PEERED_NETWORK (41): + The packet is sent to the Private Service Connect endpoint + over the peering, but `it's not + supported `__. + PSC_NEG_PRODUCER_ENDPOINT_NO_GLOBAL_ACCESS (48): + The packet is sent to the Private Service + Connect backend (network endpoint group), but + the producer PSC forwarding rule does not have + global access enabled. + PSC_NEG_PRODUCER_FORWARDING_RULE_MULTIPLE_PORTS (54): + The packet is sent to the Private Service + Connect backend (network endpoint group), but + the producer PSC forwarding rule has multiple + ports specified. + CLOUD_SQL_PSC_NEG_UNSUPPORTED (58): + The packet is sent to the Private Service + Connect backend (network endpoint group) + targeting a Cloud SQL service attachment, but + this configuration is not supported. + NO_NAT_SUBNETS_FOR_PSC_SERVICE_ATTACHMENT (57): + No NAT subnets are defined for the PSC + service attachment. + PSC_TRANSITIVITY_NOT_PROPAGATED (64): + PSC endpoint is accessed via NCC, but PSC + transitivity configuration is not yet + propagated. + HYBRID_NEG_NON_DYNAMIC_ROUTE_MATCHED (55): + The packet sent from the hybrid NEG proxy + matches a non-dynamic route, but such a + configuration is not supported. + HYBRID_NEG_NON_LOCAL_DYNAMIC_ROUTE_MATCHED (56): + The packet sent from the hybrid NEG proxy + matches a dynamic route with a next hop in a + different region, but such a configuration is + not supported. + CLOUD_RUN_REVISION_NOT_READY (29): + Packet sent from a Cloud Run revision that is + not ready. + DROPPED_INSIDE_PSC_SERVICE_PRODUCER (37): + Packet was dropped inside Private Service + Connect service producer. + LOAD_BALANCER_HAS_NO_PROXY_SUBNET (39): + Packet sent to a load balancer, which + requires a proxy-only subnet and the subnet is + not found. + CLOUD_NAT_NO_ADDRESSES (40): + Packet sent to Cloud Nat without active NAT + IPs. + ROUTING_LOOP (59): + Packet is stuck in a routing loop. + DROPPED_INSIDE_GOOGLE_MANAGED_SERVICE (62): + Packet is dropped inside a Google-managed + service due to being delivered in return trace + to an endpoint that doesn't match the endpoint + the packet was sent from in forward trace. Used + only for return traces. + LOAD_BALANCER_BACKEND_INVALID_NETWORK (65): + Packet is dropped due to a load balancer + backend instance not having a network interface + in the network expected by the load balancer. + BACKEND_SERVICE_NAMED_PORT_NOT_DEFINED (66): + Packet is dropped due to a backend service + named port not being defined on the instance + group level. + DESTINATION_IS_PRIVATE_NAT_IP_RANGE (67): + Packet is dropped due to a destination IP + range being part of a Private NAT IP range. + DROPPED_INSIDE_REDIS_INSTANCE_SERVICE (70): + Generic drop cause for a packet being dropped + inside a Redis Instance service project. + REDIS_INSTANCE_UNSUPPORTED_PORT (71): + Packet is dropped due to an unsupported port + being used to connect to a Redis Instance. Port + 6379 should be used to connect to a Redis + Instance. + REDIS_INSTANCE_CONNECTING_FROM_PUPI_ADDRESS (72): + Packet is dropped due to connecting from PUPI + address to a PSA based Redis Instance. + REDIS_INSTANCE_NO_ROUTE_TO_DESTINATION_NETWORK (73): + Packet is dropped due to no route to the + destination network. + REDIS_INSTANCE_NO_EXTERNAL_IP (74): + Redis Instance does not have an external IP + address. + REDIS_INSTANCE_UNSUPPORTED_PROTOCOL (78): + Packet is dropped due to an unsupported + protocol being used to connect to a Redis + Instance. Only TCP connections are accepted by a + Redis Instance. + DROPPED_INSIDE_REDIS_CLUSTER_SERVICE (75): + Generic drop cause for a packet being dropped + inside a Redis Cluster service project. + REDIS_CLUSTER_UNSUPPORTED_PORT (76): + Packet is dropped due to an unsupported port + being used to connect to a Redis Cluster. Ports + 6379 and 11000 to 13047 should be used to + connect to a Redis Cluster. + REDIS_CLUSTER_NO_EXTERNAL_IP (77): + Redis Cluster does not have an external IP + address. + REDIS_CLUSTER_UNSUPPORTED_PROTOCOL (79): + Packet is dropped due to an unsupported + protocol being used to connect to a Redis + Cluster. Only TCP connections are accepted by a + Redis Cluster. + NO_ADVERTISED_ROUTE_TO_GCP_DESTINATION (80): + Packet from the non-GCP (on-prem) or unknown + GCP network is dropped due to the destination IP + address not belonging to any IP prefix + advertised via BGP by the Cloud Router. + NO_TRAFFIC_SELECTOR_TO_GCP_DESTINATION (81): + Packet from the non-GCP (on-prem) or unknown + GCP network is dropped due to the destination IP + address not belonging to any IP prefix included + to the local traffic selector of the VPN tunnel. + NO_KNOWN_ROUTE_FROM_PEERED_NETWORK_TO_DESTINATION (82): + Packet from the unknown peered network is + dropped due to no known route from the source + network to the destination IP address. + PRIVATE_NAT_TO_PSC_ENDPOINT_UNSUPPORTED (83): + Sending packets processed by the Private NAT + Gateways to the Private Service Connect + endpoints is not supported. + """ + CAUSE_UNSPECIFIED = 0 + UNKNOWN_EXTERNAL_ADDRESS = 1 + FOREIGN_IP_DISALLOWED = 2 + FIREWALL_RULE = 3 + NO_ROUTE = 4 + ROUTE_BLACKHOLE = 5 + ROUTE_WRONG_NETWORK = 6 + ROUTE_NEXT_HOP_IP_ADDRESS_NOT_RESOLVED = 42 + ROUTE_NEXT_HOP_RESOURCE_NOT_FOUND = 43 + ROUTE_NEXT_HOP_INSTANCE_WRONG_NETWORK = 49 + ROUTE_NEXT_HOP_INSTANCE_NON_PRIMARY_IP = 50 + ROUTE_NEXT_HOP_FORWARDING_RULE_IP_MISMATCH = 51 + ROUTE_NEXT_HOP_VPN_TUNNEL_NOT_ESTABLISHED = 52 + ROUTE_NEXT_HOP_FORWARDING_RULE_TYPE_INVALID = 53 + NO_ROUTE_FROM_INTERNET_TO_PRIVATE_IPV6_ADDRESS = 44 + VPN_TUNNEL_LOCAL_SELECTOR_MISMATCH = 45 + VPN_TUNNEL_REMOTE_SELECTOR_MISMATCH = 46 + PRIVATE_TRAFFIC_TO_INTERNET = 7 + PRIVATE_GOOGLE_ACCESS_DISALLOWED = 8 + PRIVATE_GOOGLE_ACCESS_VIA_VPN_TUNNEL_UNSUPPORTED = 47 + NO_EXTERNAL_ADDRESS = 9 + UNKNOWN_INTERNAL_ADDRESS = 10 + FORWARDING_RULE_MISMATCH = 11 + FORWARDING_RULE_NO_INSTANCES = 12 + FIREWALL_BLOCKING_LOAD_BALANCER_BACKEND_HEALTH_CHECK = 13 + INSTANCE_NOT_RUNNING = 14 + GKE_CLUSTER_NOT_RUNNING = 27 + CLOUD_SQL_INSTANCE_NOT_RUNNING = 28 + REDIS_INSTANCE_NOT_RUNNING = 68 + REDIS_CLUSTER_NOT_RUNNING = 69 + TRAFFIC_TYPE_BLOCKED = 15 + GKE_MASTER_UNAUTHORIZED_ACCESS = 16 + CLOUD_SQL_INSTANCE_UNAUTHORIZED_ACCESS = 17 + DROPPED_INSIDE_GKE_SERVICE = 18 + DROPPED_INSIDE_CLOUD_SQL_SERVICE = 19 + GOOGLE_MANAGED_SERVICE_NO_PEERING = 20 + GOOGLE_MANAGED_SERVICE_NO_PSC_ENDPOINT = 38 + GKE_PSC_ENDPOINT_MISSING = 36 + CLOUD_SQL_INSTANCE_NO_IP_ADDRESS = 21 + GKE_CONTROL_PLANE_REGION_MISMATCH = 30 + PUBLIC_GKE_CONTROL_PLANE_TO_PRIVATE_DESTINATION = 31 + GKE_CONTROL_PLANE_NO_ROUTE = 32 + CLOUD_SQL_INSTANCE_NOT_CONFIGURED_FOR_EXTERNAL_TRAFFIC = 33 + PUBLIC_CLOUD_SQL_INSTANCE_TO_PRIVATE_DESTINATION = 34 + CLOUD_SQL_INSTANCE_NO_ROUTE = 35 + CLOUD_SQL_CONNECTOR_REQUIRED = 63 + CLOUD_FUNCTION_NOT_ACTIVE = 22 + VPC_CONNECTOR_NOT_SET = 23 + VPC_CONNECTOR_NOT_RUNNING = 24 + VPC_CONNECTOR_SERVERLESS_TRAFFIC_BLOCKED = 60 + VPC_CONNECTOR_HEALTH_CHECK_TRAFFIC_BLOCKED = 61 + FORWARDING_RULE_REGION_MISMATCH = 25 + PSC_CONNECTION_NOT_ACCEPTED = 26 + PSC_ENDPOINT_ACCESSED_FROM_PEERED_NETWORK = 41 + PSC_NEG_PRODUCER_ENDPOINT_NO_GLOBAL_ACCESS = 48 + PSC_NEG_PRODUCER_FORWARDING_RULE_MULTIPLE_PORTS = 54 + CLOUD_SQL_PSC_NEG_UNSUPPORTED = 58 + NO_NAT_SUBNETS_FOR_PSC_SERVICE_ATTACHMENT = 57 + PSC_TRANSITIVITY_NOT_PROPAGATED = 64 + HYBRID_NEG_NON_DYNAMIC_ROUTE_MATCHED = 55 + HYBRID_NEG_NON_LOCAL_DYNAMIC_ROUTE_MATCHED = 56 + CLOUD_RUN_REVISION_NOT_READY = 29 + DROPPED_INSIDE_PSC_SERVICE_PRODUCER = 37 + LOAD_BALANCER_HAS_NO_PROXY_SUBNET = 39 + CLOUD_NAT_NO_ADDRESSES = 40 + ROUTING_LOOP = 59 + DROPPED_INSIDE_GOOGLE_MANAGED_SERVICE = 62 + LOAD_BALANCER_BACKEND_INVALID_NETWORK = 65 + BACKEND_SERVICE_NAMED_PORT_NOT_DEFINED = 66 + DESTINATION_IS_PRIVATE_NAT_IP_RANGE = 67 + DROPPED_INSIDE_REDIS_INSTANCE_SERVICE = 70 + REDIS_INSTANCE_UNSUPPORTED_PORT = 71 + REDIS_INSTANCE_CONNECTING_FROM_PUPI_ADDRESS = 72 + REDIS_INSTANCE_NO_ROUTE_TO_DESTINATION_NETWORK = 73 + REDIS_INSTANCE_NO_EXTERNAL_IP = 74 + REDIS_INSTANCE_UNSUPPORTED_PROTOCOL = 78 + DROPPED_INSIDE_REDIS_CLUSTER_SERVICE = 75 + REDIS_CLUSTER_UNSUPPORTED_PORT = 76 + REDIS_CLUSTER_NO_EXTERNAL_IP = 77 + REDIS_CLUSTER_UNSUPPORTED_PROTOCOL = 79 + NO_ADVERTISED_ROUTE_TO_GCP_DESTINATION = 80 + NO_TRAFFIC_SELECTOR_TO_GCP_DESTINATION = 81 + NO_KNOWN_ROUTE_FROM_PEERED_NETWORK_TO_DESTINATION = 82 + PRIVATE_NAT_TO_PSC_ENDPOINT_UNSUPPORTED = 83 + + cause: Cause = proto.Field( + proto.ENUM, + number=1, + enum=Cause, + ) + resource_uri: str = proto.Field( + proto.STRING, + number=2, + ) + source_ip: str = proto.Field( + proto.STRING, + number=3, + ) + destination_ip: str = proto.Field( + proto.STRING, + number=4, + ) + region: str = proto.Field( + proto.STRING, + number=5, + ) + + +class GKEMasterInfo(proto.Message): + r"""For display only. Metadata associated with a Google + Kubernetes Engine (GKE) cluster master. + + Attributes: + cluster_uri (str): + URI of a GKE cluster. + cluster_network_uri (str): + URI of a GKE cluster network. + internal_ip (str): + Internal IP address of a GKE cluster control + plane. + external_ip (str): + External IP address of a GKE cluster control + plane. + dns_endpoint (str): + DNS endpoint of a GKE cluster control plane. + """ + + cluster_uri: str = proto.Field( + proto.STRING, + number=2, + ) + cluster_network_uri: str = proto.Field( + proto.STRING, + number=4, + ) + internal_ip: str = proto.Field( + proto.STRING, + number=5, + ) + external_ip: str = proto.Field( + proto.STRING, + number=6, + ) + dns_endpoint: str = proto.Field( + proto.STRING, + number=7, + ) + + +class CloudSQLInstanceInfo(proto.Message): + r"""For display only. Metadata associated with a Cloud SQL + instance. + + Attributes: + display_name (str): + Name of a Cloud SQL instance. + uri (str): + URI of a Cloud SQL instance. + network_uri (str): + URI of a Cloud SQL instance network or empty + string if the instance does not have one. + internal_ip (str): + Internal IP address of a Cloud SQL instance. + external_ip (str): + External IP address of a Cloud SQL instance. + region (str): + Region in which the Cloud SQL instance is + running. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + network_uri: str = proto.Field( + proto.STRING, + number=4, + ) + internal_ip: str = proto.Field( + proto.STRING, + number=5, + ) + external_ip: str = proto.Field( + proto.STRING, + number=6, + ) + region: str = proto.Field( + proto.STRING, + number=7, + ) + + +class RedisInstanceInfo(proto.Message): + r"""For display only. Metadata associated with a Cloud Redis + Instance. + + Attributes: + display_name (str): + Name of a Cloud Redis Instance. + uri (str): + URI of a Cloud Redis Instance. + network_uri (str): + URI of a Cloud Redis Instance network. + primary_endpoint_ip (str): + Primary endpoint IP address of a Cloud Redis + Instance. + read_endpoint_ip (str): + Read endpoint IP address of a Cloud Redis + Instance (if applicable). + region (str): + Region in which the Cloud Redis Instance is + defined. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + network_uri: str = proto.Field( + proto.STRING, + number=3, + ) + primary_endpoint_ip: str = proto.Field( + proto.STRING, + number=4, + ) + read_endpoint_ip: str = proto.Field( + proto.STRING, + number=5, + ) + region: str = proto.Field( + proto.STRING, + number=6, + ) + + +class RedisClusterInfo(proto.Message): + r"""For display only. Metadata associated with a Redis Cluster. + + Attributes: + display_name (str): + Name of a Redis Cluster. + uri (str): + URI of a Redis Cluster in format + "projects/{project_id}/locations/{location}/clusters/{cluster_id}". + network_uri (str): + URI of a Redis Cluster network in format + "projects/{project_id}/global/networks/{network_id}". + discovery_endpoint_ip_address (str): + Discovery endpoint IP address of a Redis + Cluster. + secondary_endpoint_ip_address (str): + Secondary endpoint IP address of a Redis + Cluster. + location (str): + Name of the region in which the Redis Cluster + is defined. For example, "us-central1". + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + network_uri: str = proto.Field( + proto.STRING, + number=3, + ) + discovery_endpoint_ip_address: str = proto.Field( + proto.STRING, + number=4, + ) + secondary_endpoint_ip_address: str = proto.Field( + proto.STRING, + number=5, + ) + location: str = proto.Field( + proto.STRING, + number=6, + ) + + +class CloudFunctionInfo(proto.Message): + r"""For display only. Metadata associated with a Cloud Function. + + Attributes: + display_name (str): + Name of a Cloud Function. + uri (str): + URI of a Cloud Function. + location (str): + Location in which the Cloud Function is + deployed. + version_id (int): + Latest successfully deployed version id of + the Cloud Function. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + location: str = proto.Field( + proto.STRING, + number=3, + ) + version_id: int = proto.Field( + proto.INT64, + number=4, + ) + + +class CloudRunRevisionInfo(proto.Message): + r"""For display only. Metadata associated with a Cloud Run + revision. + + Attributes: + display_name (str): + Name of a Cloud Run revision. + uri (str): + URI of a Cloud Run revision. + location (str): + Location in which this revision is deployed. + service_uri (str): + URI of Cloud Run service this revision + belongs to. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + location: str = proto.Field( + proto.STRING, + number=4, + ) + service_uri: str = proto.Field( + proto.STRING, + number=5, + ) + + +class AppEngineVersionInfo(proto.Message): + r"""For display only. Metadata associated with an App Engine + version. + + Attributes: + display_name (str): + Name of an App Engine version. + uri (str): + URI of an App Engine version. + runtime (str): + Runtime of the App Engine version. + environment (str): + App Engine execution environment for a + version. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + runtime: str = proto.Field( + proto.STRING, + number=3, + ) + environment: str = proto.Field( + proto.STRING, + number=4, + ) + + +class VpcConnectorInfo(proto.Message): + r"""For display only. Metadata associated with a VPC connector. + + Attributes: + display_name (str): + Name of a VPC connector. + uri (str): + URI of a VPC connector. + location (str): + Location in which the VPC connector is + deployed. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + location: str = proto.Field( + proto.STRING, + number=3, + ) + + +class NatInfo(proto.Message): + r"""For display only. Metadata associated with NAT. + + Attributes: + type_ (google.cloud.network_management_v1.types.NatInfo.Type): + Type of NAT. + protocol (str): + IP protocol in string format, for example: + "TCP", "UDP", "ICMP". + network_uri (str): + URI of the network where NAT translation + takes place. + old_source_ip (str): + Source IP address before NAT translation. + new_source_ip (str): + Source IP address after NAT translation. + old_destination_ip (str): + Destination IP address before NAT + translation. + new_destination_ip (str): + Destination IP address after NAT translation. + old_source_port (int): + Source port before NAT translation. Only + valid when protocol is TCP or UDP. + new_source_port (int): + Source port after NAT translation. Only valid + when protocol is TCP or UDP. + old_destination_port (int): + Destination port before NAT translation. Only + valid when protocol is TCP or UDP. + new_destination_port (int): + Destination port after NAT translation. Only + valid when protocol is TCP or UDP. + router_uri (str): + Uri of the Cloud Router. Only valid when type is CLOUD_NAT. + nat_gateway_name (str): + The name of Cloud NAT Gateway. Only valid when type is + CLOUD_NAT. + """ + class Type(proto.Enum): + r"""Types of NAT. + + Values: + TYPE_UNSPECIFIED (0): + Type is unspecified. + INTERNAL_TO_EXTERNAL (1): + From Compute Engine instance's internal + address to external address. + EXTERNAL_TO_INTERNAL (2): + From Compute Engine instance's external + address to internal address. + CLOUD_NAT (3): + Cloud NAT Gateway. + PRIVATE_SERVICE_CONNECT (4): + Private service connect NAT. + """ + TYPE_UNSPECIFIED = 0 + INTERNAL_TO_EXTERNAL = 1 + EXTERNAL_TO_INTERNAL = 2 + CLOUD_NAT = 3 + PRIVATE_SERVICE_CONNECT = 4 + + type_: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + protocol: str = proto.Field( + proto.STRING, + number=2, + ) + network_uri: str = proto.Field( + proto.STRING, + number=3, + ) + old_source_ip: str = proto.Field( + proto.STRING, + number=4, + ) + new_source_ip: str = proto.Field( + proto.STRING, + number=5, + ) + old_destination_ip: str = proto.Field( + proto.STRING, + number=6, + ) + new_destination_ip: str = proto.Field( + proto.STRING, + number=7, + ) + old_source_port: int = proto.Field( + proto.INT32, + number=8, + ) + new_source_port: int = proto.Field( + proto.INT32, + number=9, + ) + old_destination_port: int = proto.Field( + proto.INT32, + number=10, + ) + new_destination_port: int = proto.Field( + proto.INT32, + number=11, + ) + router_uri: str = proto.Field( + proto.STRING, + number=12, + ) + nat_gateway_name: str = proto.Field( + proto.STRING, + number=13, + ) + + +class ProxyConnectionInfo(proto.Message): + r"""For display only. Metadata associated with ProxyConnection. + + Attributes: + protocol (str): + IP protocol in string format, for example: + "TCP", "UDP", "ICMP". + old_source_ip (str): + Source IP address of an original connection. + new_source_ip (str): + Source IP address of a new connection. + old_destination_ip (str): + Destination IP address of an original + connection + new_destination_ip (str): + Destination IP address of a new connection. + old_source_port (int): + Source port of an original connection. Only + valid when protocol is TCP or UDP. + new_source_port (int): + Source port of a new connection. Only valid + when protocol is TCP or UDP. + old_destination_port (int): + Destination port of an original connection. + Only valid when protocol is TCP or UDP. + new_destination_port (int): + Destination port of a new connection. Only + valid when protocol is TCP or UDP. + subnet_uri (str): + Uri of proxy subnet. + network_uri (str): + URI of the network where connection is + proxied. + """ + + protocol: str = proto.Field( + proto.STRING, + number=1, + ) + old_source_ip: str = proto.Field( + proto.STRING, + number=2, + ) + new_source_ip: str = proto.Field( + proto.STRING, + number=3, + ) + old_destination_ip: str = proto.Field( + proto.STRING, + number=4, + ) + new_destination_ip: str = proto.Field( + proto.STRING, + number=5, + ) + old_source_port: int = proto.Field( + proto.INT32, + number=6, + ) + new_source_port: int = proto.Field( + proto.INT32, + number=7, + ) + old_destination_port: int = proto.Field( + proto.INT32, + number=8, + ) + new_destination_port: int = proto.Field( + proto.INT32, + number=9, + ) + subnet_uri: str = proto.Field( + proto.STRING, + number=10, + ) + network_uri: str = proto.Field( + proto.STRING, + number=11, + ) + + +class LoadBalancerBackendInfo(proto.Message): + r"""For display only. Metadata associated with the load balancer + backend. + + Attributes: + name (str): + Display name of the backend. For example, it + might be an instance name for the instance group + backends, or an IP address and port for zonal + network endpoint group backends. + instance_uri (str): + URI of the backend instance (if applicable). + Populated for instance group backends, and zonal + NEG backends. + backend_service_uri (str): + URI of the backend service this backend + belongs to (if applicable). + instance_group_uri (str): + URI of the instance group this backend + belongs to (if applicable). + network_endpoint_group_uri (str): + URI of the network endpoint group this + backend belongs to (if applicable). + backend_bucket_uri (str): + URI of the backend bucket this backend + targets (if applicable). + psc_service_attachment_uri (str): + URI of the PSC service attachment this PSC + NEG backend targets (if applicable). + psc_google_api_target (str): + PSC Google API target this PSC NEG backend + targets (if applicable). + health_check_uri (str): + URI of the health check attached to this + backend (if applicable). + health_check_firewalls_config_state (google.cloud.network_management_v1.types.LoadBalancerBackendInfo.HealthCheckFirewallsConfigState): + Output only. Health check firewalls + configuration state for the backend. This is a + result of the static firewall analysis + (verifying that health check traffic from + required IP ranges to the backend is allowed or + not). The backend might still be unhealthy even + if these firewalls are configured. Please refer + to the documentation for more information: + + https://cloud.google.com/load-balancing/docs/firewall-rules + """ + class HealthCheckFirewallsConfigState(proto.Enum): + r"""Health check firewalls configuration state enum. + + Values: + HEALTH_CHECK_FIREWALLS_CONFIG_STATE_UNSPECIFIED (0): + Configuration state unspecified. It usually + means that the backend has no health check + attached, or there was an unexpected + configuration error preventing Connectivity + tests from verifying health check configuration. + FIREWALLS_CONFIGURED (1): + Firewall rules (policies) allowing health + check traffic from all required IP ranges to the + backend are configured. + FIREWALLS_PARTIALLY_CONFIGURED (2): + Firewall rules (policies) allow health check + traffic only from a part of required IP ranges. + FIREWALLS_NOT_CONFIGURED (3): + Firewall rules (policies) deny health check + traffic from all required IP ranges to the + backend. + FIREWALLS_UNSUPPORTED (4): + The network contains firewall rules of + unsupported types, so Connectivity tests were + not able to verify health check configuration + status. Please refer to the documentation for + the list of unsupported configurations: + + https://cloud.google.com/network-intelligence-center/docs/connectivity-tests/concepts/overview#unsupported-configs + """ + HEALTH_CHECK_FIREWALLS_CONFIG_STATE_UNSPECIFIED = 0 + FIREWALLS_CONFIGURED = 1 + FIREWALLS_PARTIALLY_CONFIGURED = 2 + FIREWALLS_NOT_CONFIGURED = 3 + FIREWALLS_UNSUPPORTED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + instance_uri: str = proto.Field( + proto.STRING, + number=2, + ) + backend_service_uri: str = proto.Field( + proto.STRING, + number=3, + ) + instance_group_uri: str = proto.Field( + proto.STRING, + number=4, + ) + network_endpoint_group_uri: str = proto.Field( + proto.STRING, + number=5, + ) + backend_bucket_uri: str = proto.Field( + proto.STRING, + number=8, + ) + psc_service_attachment_uri: str = proto.Field( + proto.STRING, + number=9, + ) + psc_google_api_target: str = proto.Field( + proto.STRING, + number=10, + ) + health_check_uri: str = proto.Field( + proto.STRING, + number=6, + ) + health_check_firewalls_config_state: HealthCheckFirewallsConfigState = proto.Field( + proto.ENUM, + number=7, + enum=HealthCheckFirewallsConfigState, + ) + + +class StorageBucketInfo(proto.Message): + r"""For display only. Metadata associated with Storage Bucket. + + Attributes: + bucket (str): + Cloud Storage Bucket name. + """ + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ServerlessNegInfo(proto.Message): + r"""For display only. Metadata associated with the serverless + network endpoint group backend. + + Attributes: + neg_uri (str): + URI of the serverless network endpoint group. + """ + + neg_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/mypy.ini b/owl-bot-staging/google-cloud-network-management/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-management/v1/noxfile.py b/owl-bot-staging/google-cloud-network-management/v1/noxfile.py new file mode 100644 index 000000000000..e09f07364b34 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/noxfile.py @@ -0,0 +1,280 @@ +# -*- 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-network-management' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/network_management_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/network_management_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-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py new file mode 100644 index 000000000000..c74b86142f00 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py @@ -0,0 +1,57 @@ +# -*- 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 CreateConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_create_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.CreateConnectivityTestRequest( + parent="parent_value", + test_id="test_id_value", + ) + + # Make the request + operation = client.create_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py new file mode 100644 index 000000000000..c27c11cc246a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py @@ -0,0 +1,57 @@ +# -*- 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 CreateConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_create_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.CreateConnectivityTestRequest( + parent="parent_value", + test_id="test_id_value", + ) + + # Make the request + operation = client.create_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py new file mode 100644 index 000000000000..cc7d4daf1552 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_delete_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.DeleteConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py new file mode 100644 index 000000000000..00d6602a4aef --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_delete_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.DeleteConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py new file mode 100644 index 000000000000..85b70752cf16 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py @@ -0,0 +1,52 @@ +# -*- 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 GetConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_get_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.GetConnectivityTestRequest( + name="name_value", + ) + + # Make the request + response = await client.get_connectivity_test(request=request) + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py new file mode 100644 index 000000000000..40673d28a839 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py @@ -0,0 +1,52 @@ +# -*- 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 GetConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_get_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.GetConnectivityTestRequest( + name="name_value", + ) + + # Make the request + response = client.get_connectivity_test(request=request) + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py new file mode 100644 index 000000000000..15d2f1f0232f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py @@ -0,0 +1,53 @@ +# -*- 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 ListConnectivityTests +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_list_connectivity_tests(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.ListConnectivityTestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_connectivity_tests(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py new file mode 100644 index 000000000000..c595e917f169 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py @@ -0,0 +1,53 @@ +# -*- 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 ListConnectivityTests +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_list_connectivity_tests(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.ListConnectivityTestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_connectivity_tests(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py new file mode 100644 index 000000000000..9ba7e4c6759f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py @@ -0,0 +1,56 @@ +# -*- 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 RerunConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_rerun_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.RerunConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.rerun_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py new file mode 100644 index 000000000000..c726b18eda73 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py @@ -0,0 +1,56 @@ +# -*- 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 RerunConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_rerun_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.RerunConnectivityTestRequest( + name="name_value", + ) + + # Make the request + operation = client.rerun_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py new file mode 100644 index 000000000000..a89f65bf0aa0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py @@ -0,0 +1,55 @@ +# -*- 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 UpdateConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +async def sample_update_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceAsyncClient() + + # Initialize request argument(s) + request = network_management_v1.UpdateConnectivityTestRequest( + ) + + # Make the request + operation = client.update_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py new file mode 100644 index 000000000000..503f72cf246b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py @@ -0,0 +1,55 @@ +# -*- 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 UpdateConnectivityTest +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-management + + +# [START networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_management_v1 + + +def sample_update_connectivity_test(): + # Create a client + client = network_management_v1.ReachabilityServiceClient() + + # Initialize request argument(s) + request = network_management_v1.UpdateConnectivityTestRequest( + ) + + # Make the request + operation = client.update_connectivity_test(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json new file mode 100644 index 000000000000..a6a39ec02f7f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json @@ -0,0 +1,997 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.networkmanagement.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-network-management", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.create_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.CreateConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "CreateConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.CreateConnectivityTestRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "test_id", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.network_management_v1.types.ConnectivityTest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for CreateConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.create_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.CreateConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "CreateConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.CreateConnectivityTestRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "test_id", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.network_management_v1.types.ConnectivityTest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for CreateConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.delete_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.DeleteConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "DeleteConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.DeleteConnectivityTestRequest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for DeleteConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.delete_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.DeleteConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "DeleteConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.DeleteConnectivityTestRequest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for DeleteConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.get_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.GetConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "GetConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.GetConnectivityTestRequest" + }, + { + "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.network_management_v1.types.ConnectivityTest", + "shortName": "get_connectivity_test" + }, + "description": "Sample for GetConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.get_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.GetConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "GetConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.GetConnectivityTestRequest" + }, + { + "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.network_management_v1.types.ConnectivityTest", + "shortName": "get_connectivity_test" + }, + "description": "Sample for GetConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.list_connectivity_tests", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.ListConnectivityTests", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "ListConnectivityTests" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.ListConnectivityTestsRequest" + }, + { + "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.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsAsyncPager", + "shortName": "list_connectivity_tests" + }, + "description": "Sample for ListConnectivityTests", + "file": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_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": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.list_connectivity_tests", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.ListConnectivityTests", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "ListConnectivityTests" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.ListConnectivityTestsRequest" + }, + { + "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.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsPager", + "shortName": "list_connectivity_tests" + }, + "description": "Sample for ListConnectivityTests", + "file": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_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": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.rerun_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.RerunConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "RerunConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.RerunConnectivityTestRequest" + }, + { + "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": "rerun_connectivity_test" + }, + "description": "Sample for RerunConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.rerun_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.RerunConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "RerunConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.RerunConnectivityTestRequest" + }, + { + "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": "rerun_connectivity_test" + }, + "description": "Sample for RerunConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", + "shortName": "ReachabilityServiceAsyncClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.update_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.UpdateConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "UpdateConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.UpdateConnectivityTestRequest" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "resource", + "type": "google.cloud.network_management_v1.types.ConnectivityTest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for UpdateConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", + "shortName": "ReachabilityServiceClient" + }, + "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.update_connectivity_test", + "method": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.UpdateConnectivityTest", + "service": { + "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", + "shortName": "ReachabilityService" + }, + "shortName": "UpdateConnectivityTest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_management_v1.types.UpdateConnectivityTestRequest" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "resource", + "type": "google.cloud.network_management_v1.types.ConnectivityTest" + }, + { + "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_connectivity_test" + }, + "description": "Sample for UpdateConnectivityTest", + "file": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py b/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py new file mode 100644 index 000000000000..33791cd81e72 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py @@ -0,0 +1,181 @@ +#! /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 network_managementCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_connectivity_test': ('parent', 'test_id', 'resource', ), + 'delete_connectivity_test': ('name', ), + 'get_connectivity_test': ('name', ), + 'list_connectivity_tests': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'rerun_connectivity_test': ('name', ), + 'update_connectivity_test': ('update_mask', 'resource', ), + } + + 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=network_managementCallTransformer(), +): + """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 network_management 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-network-management/v1/setup.py b/owl-bot-staging/google-cloud-network-management/v1/setup.py new file mode 100644 index 000000000000..110a46599b9a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/setup.py @@ -0,0 +1,99 @@ +# -*- 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-network-management' + + +description = "Google Cloud Network Management API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/network_management/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-management" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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-network-management/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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-network-management/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py new file mode 100644 index 000000000000..b5d474b02375 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py @@ -0,0 +1,7469 @@ +# -*- 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.location import locations_pb2 +from google.cloud.network_management_v1.services.reachability_service import ReachabilityServiceAsyncClient +from google.cloud.network_management_v1.services.reachability_service import ReachabilityServiceClient +from google.cloud.network_management_v1.services.reachability_service import pagers +from google.cloud.network_management_v1.services.reachability_service import transports +from google.cloud.network_management_v1.types import connectivity_test +from google.cloud.network_management_v1.types import reachability +from google.cloud.network_management_v1.types import trace +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import 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 ReachabilityServiceClient._get_default_mtls_endpoint(None) is None + assert ReachabilityServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ReachabilityServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ReachabilityServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ReachabilityServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ReachabilityServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ReachabilityServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ReachabilityServiceClient._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 ReachabilityServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ReachabilityServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ReachabilityServiceClient._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 ReachabilityServiceClient._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 ReachabilityServiceClient._get_client_cert_source(None, False) is None + assert ReachabilityServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ReachabilityServiceClient._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 ReachabilityServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ReachabilityServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) +@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ReachabilityServiceClient._DEFAULT_UNIVERSE + default_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ReachabilityServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ReachabilityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT + assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "always") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT + assert ReachabilityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT + assert ReachabilityServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ReachabilityServiceClient._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 ReachabilityServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ReachabilityServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ReachabilityServiceClient._get_universe_domain(None, None) == ReachabilityServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ReachabilityServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ReachabilityServiceClient, "grpc"), + (ReachabilityServiceAsyncClient, "grpc_asyncio"), + (ReachabilityServiceClient, "rest"), +]) +def test_reachability_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networkmanagement.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networkmanagement.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ReachabilityServiceGrpcTransport, "grpc"), + (transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ReachabilityServiceRestTransport, "rest"), +]) +def test_reachability_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ReachabilityServiceClient, "grpc"), + (ReachabilityServiceAsyncClient, "grpc_asyncio"), + (ReachabilityServiceClient, "rest"), +]) +def test_reachability_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networkmanagement.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networkmanagement.googleapis.com' + ) + + +def test_reachability_service_client_get_transport_class(): + transport = ReachabilityServiceClient.get_transport_class() + available_transports = [ + transports.ReachabilityServiceGrpcTransport, + transports.ReachabilityServiceRestTransport, + ] + assert transport in available_transports + + transport = ReachabilityServiceClient.get_transport_class("grpc") + assert transport == transports.ReachabilityServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc"), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest"), +]) +@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) +@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) +def test_reachability_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ReachabilityServiceClient, '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(ReachabilityServiceClient, '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", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", "true"), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", "false"), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", "true"), + (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) +@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_reachability_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ReachabilityServiceClient, ReachabilityServiceAsyncClient +]) +@mock.patch.object(ReachabilityServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReachabilityServiceClient)) +@mock.patch.object(ReachabilityServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReachabilityServiceAsyncClient)) +def test_reachability_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_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", [ + ReachabilityServiceClient, ReachabilityServiceAsyncClient +]) +@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) +@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) +def test_reachability_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ReachabilityServiceClient._DEFAULT_UNIVERSE + default_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ReachabilityServiceClient._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", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc"), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest"), +]) +def test_reachability_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", grpc_helpers), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", None), +]) +def test_reachability_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_reachability_service_client_client_options_from_dict(): + with mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ReachabilityServiceClient( + 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", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", grpc_helpers), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_reachability_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networkmanagement.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="networkmanagement.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + reachability.ListConnectivityTestsRequest, + dict, +]) +def test_list_connectivity_tests(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connectivity_tests), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reachability.ListConnectivityTestsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.ListConnectivityTestsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConnectivityTestsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_connectivity_tests_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 = ReachabilityServiceClient( + 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 = reachability.ListConnectivityTestsRequest( + 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_connectivity_tests), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_connectivity_tests(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.ListConnectivityTestsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_connectivity_tests_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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_connectivity_tests in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_tests] = mock_rpc + request = {} + client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_connectivity_tests(request) + + # Establish that a new wrapper 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_connectivity_tests_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 = ReachabilityServiceAsyncClient( + 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_connectivity_tests 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_connectivity_tests] = mock_rpc + + request = {} + await client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_connectivity_tests(request) + + # Establish that a new wrapper 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_connectivity_tests_async(transport: str = 'grpc_asyncio', request_type=reachability.ListConnectivityTestsRequest): + client = ReachabilityServiceAsyncClient( + 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_connectivity_tests), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.ListConnectivityTestsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConnectivityTestsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_connectivity_tests_async_from_dict(): + await test_list_connectivity_tests_async(request_type=dict) + +def test_list_connectivity_tests_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.ListConnectivityTestsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + call.return_value = reachability.ListConnectivityTestsResponse() + client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_connectivity_tests_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.ListConnectivityTestsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse()) + await client.list_connectivity_tests(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_connectivity_tests_flattened(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reachability.ListConnectivityTestsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_connectivity_tests( + 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_connectivity_tests_flattened_error(): + client = ReachabilityServiceClient( + 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_connectivity_tests( + reachability.ListConnectivityTestsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_connectivity_tests_flattened_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reachability.ListConnectivityTestsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_connectivity_tests( + 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_connectivity_tests_flattened_error_async(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_tests( + reachability.ListConnectivityTestsRequest(), + parent='parent_value', + ) + + +def test_list_connectivity_tests_pager(transport_name: str = "grpc"): + client = ReachabilityServiceClient( + 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_connectivity_tests), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token='abc', + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token='def', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token='ghi', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_connectivity_tests(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, connectivity_test.ConnectivityTest) + for i in results) +def test_list_connectivity_tests_pages(transport_name: str = "grpc"): + client = ReachabilityServiceClient( + 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_connectivity_tests), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token='abc', + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token='def', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token='ghi', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), + RuntimeError, + ) + pages = list(client.list_connectivity_tests(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_connectivity_tests_async_pager(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token='abc', + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token='def', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token='ghi', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_connectivity_tests(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, connectivity_test.ConnectivityTest) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_connectivity_tests_async_pages(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token='abc', + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token='def', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token='ghi', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), + 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_connectivity_tests(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", [ + reachability.GetConnectivityTestRequest, + dict, +]) +def test_get_connectivity_test(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = connectivity_test.ConnectivityTest( + name='name_value', + description='description_value', + protocol='protocol_value', + related_projects=['related_projects_value'], + display_name='display_name_value', + round_trip=True, + bypass_firewall_checks=True, + ) + response = client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.GetConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, connectivity_test.ConnectivityTest) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.protocol == 'protocol_value' + assert response.related_projects == ['related_projects_value'] + assert response.display_name == 'display_name_value' + assert response.round_trip is True + assert response.bypass_firewall_checks is True + + +def test_get_connectivity_test_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 = ReachabilityServiceClient( + 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 = reachability.GetConnectivityTestRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_connectivity_test(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.GetConnectivityTestRequest( + name='name_value', + ) + +def test_get_connectivity_test_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + request = {} + client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( + 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_connectivity_test 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_connectivity_test] = mock_rpc + + request = {} + await client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.GetConnectivityTestRequest): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest( + name='name_value', + description='description_value', + protocol='protocol_value', + related_projects=['related_projects_value'], + display_name='display_name_value', + round_trip=True, + bypass_firewall_checks=True, + )) + response = await client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.GetConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, connectivity_test.ConnectivityTest) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.protocol == 'protocol_value' + assert response.related_projects == ['related_projects_value'] + assert response.display_name == 'display_name_value' + assert response.round_trip is True + assert response.bypass_firewall_checks is True + + +@pytest.mark.asyncio +async def test_get_connectivity_test_async_from_dict(): + await test_get_connectivity_test_async(request_type=dict) + +def test_get_connectivity_test_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.GetConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + call.return_value = connectivity_test.ConnectivityTest() + client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_connectivity_test_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.GetConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest()) + await client.get_connectivity_test(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_connectivity_test_flattened(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = connectivity_test.ConnectivityTest() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_connectivity_test( + 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_connectivity_test_flattened_error(): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.GetConnectivityTestRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_connectivity_test_flattened_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = connectivity_test.ConnectivityTest() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_connectivity_test( + 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_connectivity_test_flattened_error_async(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test( + reachability.GetConnectivityTestRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + reachability.CreateConnectivityTestRequest, + dict, +]) +def test_create_connectivity_test(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.CreateConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_connectivity_test_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 = ReachabilityServiceClient( + 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 = reachability.CreateConnectivityTestRequest( + parent='parent_value', + test_id='test_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_connectivity_test(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.CreateConnectivityTestRequest( + parent='parent_value', + test_id='test_id_value', + ) + +def test_create_connectivity_test_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + request = {} + client.create_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( + 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_connectivity_test 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_connectivity_test] = mock_rpc + + request = {} + await client.create_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.CreateConnectivityTestRequest): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test), + '__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_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.CreateConnectivityTestRequest() + 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_connectivity_test_async_from_dict(): + await test_create_connectivity_test_async(request_type=dict) + +def test_create_connectivity_test_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.CreateConnectivityTestRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_connectivity_test_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.CreateConnectivityTestRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_connectivity_test(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_connectivity_test_flattened(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__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_connectivity_test( + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].test_id + mock_val = 'test_id_value' + assert arg == mock_val + arg = args[0].resource + mock_val = connectivity_test.ConnectivityTest(name='name_value') + assert arg == mock_val + + +def test_create_connectivity_test_flattened_error(): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.CreateConnectivityTestRequest(), + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_connectivity_test_flattened_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__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_connectivity_test( + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].test_id + mock_val = 'test_id_value' + assert arg == mock_val + arg = args[0].resource + mock_val = connectivity_test.ConnectivityTest(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_connectivity_test_flattened_error_async(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test( + reachability.CreateConnectivityTestRequest(), + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + reachability.UpdateConnectivityTestRequest, + dict, +]) +def test_update_connectivity_test(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.UpdateConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_connectivity_test_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 = ReachabilityServiceClient( + 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 = reachability.UpdateConnectivityTestRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_connectivity_test(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.UpdateConnectivityTestRequest( + ) + +def test_update_connectivity_test_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + request = {} + client.update_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( + 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_connectivity_test 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_connectivity_test] = mock_rpc + + request = {} + await client.update_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.UpdateConnectivityTestRequest): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test), + '__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_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.UpdateConnectivityTestRequest() + 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_connectivity_test_async_from_dict(): + await test_update_connectivity_test_async(request_type=dict) + +def test_update_connectivity_test_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.UpdateConnectivityTestRequest() + + request.resource.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_connectivity_test_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.UpdateConnectivityTestRequest() + + request.resource.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource.name=name_value', + ) in kw['metadata'] + + +def test_update_connectivity_test_flattened(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__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_connectivity_test( + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(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].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + arg = args[0].resource + mock_val = connectivity_test.ConnectivityTest(name='name_value') + assert arg == mock_val + + +def test_update_connectivity_test_flattened_error(): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.UpdateConnectivityTestRequest(), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_connectivity_test_flattened_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__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_connectivity_test( + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(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].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + arg = args[0].resource + mock_val = connectivity_test.ConnectivityTest(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_connectivity_test_flattened_error_async(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test( + reachability.UpdateConnectivityTestRequest(), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + reachability.RerunConnectivityTestRequest, + dict, +]) +def test_rerun_connectivity_test(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rerun_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.RerunConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rerun_connectivity_test_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 = ReachabilityServiceClient( + 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 = reachability.RerunConnectivityTestRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.rerun_connectivity_test(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.RerunConnectivityTestRequest( + name='name_value', + ) + +def test_rerun_connectivity_test_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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.rerun_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.rerun_connectivity_test] = mock_rpc + request = {} + client.rerun_connectivity_test(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.rerun_connectivity_test(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_rerun_connectivity_test_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 = ReachabilityServiceAsyncClient( + 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.rerun_connectivity_test 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.rerun_connectivity_test] = mock_rpc + + request = {} + await client.rerun_connectivity_test(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.rerun_connectivity_test(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_rerun_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.RerunConnectivityTestRequest): + client = ReachabilityServiceAsyncClient( + 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.rerun_connectivity_test), + '__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.rerun_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.RerunConnectivityTestRequest() + 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_rerun_connectivity_test_async_from_dict(): + await test_rerun_connectivity_test_async(request_type=dict) + +def test_rerun_connectivity_test_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.RerunConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rerun_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_rerun_connectivity_test_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.RerunConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rerun_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + reachability.DeleteConnectivityTestRequest, + dict, +]) +def test_delete_connectivity_test(request_type, transport: str = 'grpc'): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reachability.DeleteConnectivityTestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_connectivity_test_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 = ReachabilityServiceClient( + 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 = reachability.DeleteConnectivityTestRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_connectivity_test(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reachability.DeleteConnectivityTestRequest( + name='name_value', + ) + +def test_delete_connectivity_test_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + request = {} + client.delete_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( + 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_connectivity_test 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_connectivity_test] = mock_rpc + + request = {} + await client.delete_connectivity_test(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_connectivity_test(request) + + # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.DeleteConnectivityTestRequest): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test), + '__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_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reachability.DeleteConnectivityTestRequest() + 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_connectivity_test_async_from_dict(): + await test_delete_connectivity_test_async(request_type=dict) + +def test_delete_connectivity_test_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.DeleteConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_connectivity_test_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reachability.DeleteConnectivityTestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_connectivity_test(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_connectivity_test_flattened(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__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_connectivity_test( + 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_connectivity_test_flattened_error(): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.DeleteConnectivityTestRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_connectivity_test_flattened_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__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_connectivity_test( + 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_connectivity_test_flattened_error_async(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test( + reachability.DeleteConnectivityTestRequest(), + name='name_value', + ) + + +def test_list_connectivity_tests_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 = ReachabilityServiceClient( + 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_connectivity_tests in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_tests] = mock_rpc + + request = {} + client.list_connectivity_tests(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_connectivity_tests(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_connectivity_tests_rest_required_fields(request_type=reachability.ListConnectivityTestsRequest): + transport_class = transports.ReachabilityServiceRestTransport + + 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_connectivity_tests._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_connectivity_tests._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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reachability.ListConnectivityTestsResponse() + # Mock the http request call 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_connectivity_tests_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_connectivity_tests._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_connectivity_tests_rest_flattened(): + client = ReachabilityServiceClient( + 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 = reachability.ListConnectivityTestsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/global'} + + # 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(**mock_args) + + # Establish that the underlying call 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/global}/connectivityTests" % client.transport._host, args[1]) + + +def test_list_connectivity_tests_rest_flattened_error(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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_connectivity_tests( + reachability.ListConnectivityTestsRequest(), + parent='parent_value', + ) + + +def test_list_connectivity_tests_rest_pager(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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 = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token='abc', + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token='def', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token='ghi', + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(reachability.ListConnectivityTestsResponse.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/global'} + + pager = client.list_connectivity_tests(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, connectivity_test.ConnectivityTest) + for i in results) + + pages = list(client.list_connectivity_tests(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_connectivity_test_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 = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + + request = {} + client.get_connectivity_test(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.GetConnectivityTestRequest): + transport_class = transports.ReachabilityServiceRestTransport + + 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = connectivity_test.ConnectivityTest() + # Mock the http request call 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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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 = connectivity_test.ConnectivityTest() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/global/connectivityTests/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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(**mock_args) + + # Establish that the underlying call 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/global/connectivityTests/*}" % client.transport._host, args[1]) + + +def test_get_connectivity_test_rest_flattened_error(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.GetConnectivityTestRequest(), + name='name_value', + ) + + +def test_create_connectivity_test_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 = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + + request = {} + client.create_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.CreateConnectivityTestRequest): + transport_class = transports.ReachabilityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["test_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 "testId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_connectivity_test._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "testId" in jsonified_request + assert jsonified_request["testId"] == request_init["test_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["testId"] = 'test_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_connectivity_test._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("test_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 "testId" in jsonified_request + assert jsonified_request["testId"] == 'test_id_value' + + client = ReachabilityServiceClient( + 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_connectivity_test(request) + + expected_params = [ + ( + "testId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(("testId", )) & set(("parent", "testId", "resource", ))) + + +def test_create_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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/global'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(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.create_connectivity_test(**mock_args) + + # Establish that the underlying call 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/global}/connectivityTests" % client.transport._host, args[1]) + + +def test_create_connectivity_test_rest_flattened_error(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.CreateConnectivityTestRequest(), + parent='parent_value', + test_id='test_id_value', + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + +def test_update_connectivity_test_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 = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + + request = {} + client.update_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.UpdateConnectivityTestRequest): + transport_class = transports.ReachabilityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_connectivity_test._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_connectivity_test._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_connectivity_test(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", "resource", ))) + + +def test_update_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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 = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(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.update_connectivity_test(**mock_args) + + # Establish that the underlying call 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/{resource.name=projects/*/locations/global/connectivityTests/*}" % client.transport._host, args[1]) + + +def test_update_connectivity_test_rest_flattened_error(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.UpdateConnectivityTestRequest(), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + resource=connectivity_test.ConnectivityTest(name='name_value'), + ) + + +def test_rerun_connectivity_test_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 = ReachabilityServiceClient( + 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.rerun_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.rerun_connectivity_test] = mock_rpc + + request = {} + client.rerun_connectivity_test(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.rerun_connectivity_test(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_rerun_connectivity_test_rest_required_fields(request_type=reachability.RerunConnectivityTestRequest): + transport_class = transports.ReachabilityServiceRestTransport + + 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()).rerun_connectivity_test._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()).rerun_connectivity_test._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 = ReachabilityServiceClient( + 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.rerun_connectivity_test(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_rerun_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.rerun_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_connectivity_test_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 = ReachabilityServiceClient( + 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_connectivity_test in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_connectivity_test] = mock_rpc + + request = {} + client.delete_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.DeleteConnectivityTestRequest): + transport_class = transports.ReachabilityServiceRestTransport + + 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( + 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_connectivity_test(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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/global/connectivityTests/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_connectivity_test(**mock_args) + + # Establish that the underlying call 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/global/connectivityTests/*}" % client.transport._host, args[1]) + + +def test_delete_connectivity_test_rest_flattened_error(transport: str = 'rest'): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.DeleteConnectivityTestRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ReachabilityServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ReachabilityServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ReachabilityServiceGrpcTransport, + transports.ReachabilityServiceGrpcAsyncIOTransport, + transports.ReachabilityServiceRestTransport, +]) +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 = ReachabilityServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ReachabilityServiceClient( + 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_connectivity_tests_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + call.return_value = reachability.ListConnectivityTestsResponse() + client.list_connectivity_tests(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.ListConnectivityTestsRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + call.return_value = connectivity_test.ConnectivityTest() + client.get_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.GetConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.CreateConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.UpdateConnectivityTestRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rerun_connectivity_test_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rerun_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.RerunConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_grpc(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.DeleteConnectivityTestRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ReachabilityServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_tests_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_connectivity_tests(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.ListConnectivityTestsRequest() + + assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest( + name='name_value', + description='description_value', + protocol='protocol_value', + related_projects=['related_projects_value'], + display_name='display_name_value', + round_trip=True, + bypass_firewall_checks=True, + )) + await client.get_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.GetConnectivityTestRequest() + + assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__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_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.CreateConnectivityTestRequest() + + assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__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_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.UpdateConnectivityTestRequest() + + assert args[0] == request_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_rerun_connectivity_test_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__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.rerun_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.RerunConnectivityTestRequest() + + assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__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_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.DeleteConnectivityTestRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ReachabilityServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_connectivity_tests_rest_bad_request(request_type=reachability.ListConnectivityTestsRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/global'} + 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_connectivity_tests(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.ListConnectivityTestsRequest, + dict, +]) +def test_list_connectivity_tests_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/global'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = reachability.ListConnectivityTestsResponse( + 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConnectivityTestsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_connectivity_tests_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_list_connectivity_tests") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_list_connectivity_tests") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.ListConnectivityTestsRequest.pb(reachability.ListConnectivityTestsRequest()) + 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 = reachability.ListConnectivityTestsResponse.to_json(reachability.ListConnectivityTestsResponse()) + req.return_value.content = return_value + + request = reachability.ListConnectivityTestsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reachability.ListConnectivityTestsResponse() + + client.list_connectivity_tests(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_connectivity_test_rest_bad_request(request_type=reachability.GetConnectivityTestRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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_connectivity_test(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.GetConnectivityTestRequest, + dict, +]) +def test_get_connectivity_test_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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 = connectivity_test.ConnectivityTest( + name='name_value', + description='description_value', + protocol='protocol_value', + related_projects=['related_projects_value'], + display_name='display_name_value', + round_trip=True, + bypass_firewall_checks=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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, connectivity_test.ConnectivityTest) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.protocol == 'protocol_value' + assert response.related_projects == ['related_projects_value'] + assert response.display_name == 'display_name_value' + assert response.round_trip is True + assert response.bypass_firewall_checks is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_get_connectivity_test") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_get_connectivity_test") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.GetConnectivityTestRequest.pb(reachability.GetConnectivityTestRequest()) + 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 = connectivity_test.ConnectivityTest.to_json(connectivity_test.ConnectivityTest()) + req.return_value.content = return_value + + request = reachability.GetConnectivityTestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = connectivity_test.ConnectivityTest() + + client.get_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_connectivity_test_rest_bad_request(request_type=reachability.CreateConnectivityTestRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/global'} + 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_connectivity_test(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.CreateConnectivityTestRequest, + dict, +]) +def test_create_connectivity_test_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/global'} + request_init["resource"] = {'name': 'name_value', 'description': 'description_value', 'source': {'ip_address': 'ip_address_value', 'port': 453, 'instance': 'instance_value', 'forwarding_rule': 'forwarding_rule_value', 'forwarding_rule_target': 1, 'load_balancer_id': 'load_balancer_id_value', 'load_balancer_type': 1, 'gke_master_cluster': 'gke_master_cluster_value', 'fqdn': 'fqdn_value', 'cloud_sql_instance': 'cloud_sql_instance_value', 'redis_instance': 'redis_instance_value', 'redis_cluster': 'redis_cluster_value', 'cloud_function': {'uri': 'uri_value'}, 'app_engine_version': {'uri': 'uri_value'}, 'cloud_run_revision': {'uri': 'uri_value'}, 'network': 'network_value', 'network_type': 1, 'project_id': 'project_id_value'}, 'destination': {}, 'protocol': 'protocol_value', 'related_projects': ['related_projects_value1', 'related_projects_value2'], 'display_name': 'display_name_value', 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'reachability_details': {'result': 1, 'verify_time': {}, 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'traces': [{'endpoint_info': {'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'protocol': 'protocol_value', 'source_port': 1205, 'destination_port': 1734, 'source_network_uri': 'source_network_uri_value', 'destination_network_uri': 'destination_network_uri_value', 'source_agent_uri': 'source_agent_uri_value'}, 'steps': [{'description': 'description_value', 'state': 1, 'causes_drop': True, 'project_id': 'project_id_value', 'instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'interface': 'interface_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'network_tags': ['network_tags_value1', 'network_tags_value2'], 'service_account': 'service_account_value', 'psc_network_attachment_uri': 'psc_network_attachment_uri_value'}, 'firewall': {'display_name': 'display_name_value', 'uri': 'uri_value', 'direction': 'direction_value', 'action': 'action_value', 'priority': 898, 'network_uri': 'network_uri_value', 'target_tags': ['target_tags_value1', 'target_tags_value2'], 'target_service_accounts': ['target_service_accounts_value1', 'target_service_accounts_value2'], 'policy': 'policy_value', 'policy_uri': 'policy_uri_value', 'firewall_rule_type': 1}, 'route': {'route_type': 1, 'next_hop_type': 1, 'route_scope': 1, 'display_name': 'display_name_value', 'uri': 'uri_value', 'region': 'region_value', 'dest_ip_range': 'dest_ip_range_value', 'next_hop': 'next_hop_value', 'network_uri': 'network_uri_value', 'priority': 898, 'instance_tags': ['instance_tags_value1', 'instance_tags_value2'], 'src_ip_range': 'src_ip_range_value', 'dest_port_ranges': ['dest_port_ranges_value1', 'dest_port_ranges_value2'], 'src_port_ranges': ['src_port_ranges_value1', 'src_port_ranges_value2'], 'protocols': ['protocols_value1', 'protocols_value2'], 'ncc_hub_uri': 'ncc_hub_uri_value', 'ncc_spoke_uri': 'ncc_spoke_uri_value', 'advertised_route_source_router_uri': 'advertised_route_source_router_uri_value', 'advertised_route_next_hop_uri': 'advertised_route_next_hop_uri_value'}, 'endpoint': {}, 'google_service': {'source_ip': 'source_ip_value', 'google_service_type': 1}, 'forwarding_rule': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_protocol': 'matched_protocol_value', 'matched_port_range': 'matched_port_range_value', 'vip': 'vip_value', 'target': 'target_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'load_balancer_name': 'load_balancer_name_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'vpn_gateway': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'ip_address': 'ip_address_value', 'vpn_tunnel_uri': 'vpn_tunnel_uri_value', 'region': 'region_value'}, 'vpn_tunnel': {'display_name': 'display_name_value', 'uri': 'uri_value', 'source_gateway': 'source_gateway_value', 'remote_gateway': 'remote_gateway_value', 'remote_gateway_ip': 'remote_gateway_ip_value', 'source_gateway_ip': 'source_gateway_ip_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'routing_type': 1}, 'vpc_connector': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value'}, 'deliver': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'storage_bucket': 'storage_bucket_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'forward': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value'}, 'abort': {'cause': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'projects_missing_permission': ['projects_missing_permission_value1', 'projects_missing_permission_value2']}, 'drop': {'cause': 1, 'resource_uri': 'resource_uri_value', 'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'region': 'region_value'}, 'load_balancer': {'load_balancer_type': 1, 'health_check_uri': 'health_check_uri_value', 'backends': [{'display_name': 'display_name_value', 'uri': 'uri_value', 'health_check_firewall_state': 1, 'health_check_allowing_firewall_rules': ['health_check_allowing_firewall_rules_value1', 'health_check_allowing_firewall_rules_value2'], 'health_check_blocking_firewall_rules': ['health_check_blocking_firewall_rules_value1', 'health_check_blocking_firewall_rules_value2']}], 'backend_type': 1, 'backend_uri': 'backend_uri_value'}, 'network': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_subnet_uri': 'matched_subnet_uri_value', 'matched_ip_range': 'matched_ip_range_value', 'region': 'region_value'}, 'gke_master': {'cluster_uri': 'cluster_uri_value', 'cluster_network_uri': 'cluster_network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'dns_endpoint': 'dns_endpoint_value'}, 'cloud_sql_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'region': 'region_value'}, 'redis_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'primary_endpoint_ip': 'primary_endpoint_ip_value', 'read_endpoint_ip': 'read_endpoint_ip_value', 'region': 'region_value'}, 'redis_cluster': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'discovery_endpoint_ip_address': 'discovery_endpoint_ip_address_value', 'secondary_endpoint_ip_address': 'secondary_endpoint_ip_address_value', 'location': 'location_value'}, 'cloud_function': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'version_id': 1074}, 'app_engine_version': {'display_name': 'display_name_value', 'uri': 'uri_value', 'runtime': 'runtime_value', 'environment': 'environment_value'}, 'cloud_run_revision': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'service_uri': 'service_uri_value'}, 'nat': {'type_': 1, 'protocol': 'protocol_value', 'network_uri': 'network_uri_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'router_uri': 'router_uri_value', 'nat_gateway_name': 'nat_gateway_name_value'}, 'proxy_connection': {'protocol': 'protocol_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'subnet_uri': 'subnet_uri_value', 'network_uri': 'network_uri_value'}, 'load_balancer_backend_info': {'name': 'name_value', 'instance_uri': 'instance_uri_value', 'backend_service_uri': 'backend_service_uri_value', 'instance_group_uri': 'instance_group_uri_value', 'network_endpoint_group_uri': 'network_endpoint_group_uri_value', 'backend_bucket_uri': 'backend_bucket_uri_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value', 'health_check_uri': 'health_check_uri_value', 'health_check_firewalls_config_state': 1}, 'storage_bucket': {'bucket': 'bucket_value'}, 'serverless_neg': {'neg_uri': 'neg_uri_value'}}], 'forward_trace_id': 1679}]}, 'probing_details': {'result': 1, 'verify_time': {}, 'error': {}, 'abort_cause': 1, 'sent_probe_count': 1721, 'successful_probe_count': 2367, 'endpoint_info': {}, 'probing_latency': {'latency_percentiles': [{'percent': 753, 'latency_micros': 1500}]}, 'destination_egress_location': {'metropolitan_area': 'metropolitan_area_value'}}, 'round_trip': True, 'return_reachability_details': {}, 'bypass_firewall_checks': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = reachability.CreateConnectivityTestRequest.meta.fields["resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_create_connectivity_test") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_create_connectivity_test") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.CreateConnectivityTestRequest.pb(reachability.CreateConnectivityTestRequest()) + 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 = reachability.CreateConnectivityTestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_connectivity_test_rest_bad_request(request_type=reachability.UpdateConnectivityTestRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/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.update_connectivity_test(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.UpdateConnectivityTestRequest, + dict, +]) +def test_update_connectivity_test_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/sample2'}} + request_init["resource"] = {'name': 'projects/sample1/locations/global/connectivityTests/sample2', 'description': 'description_value', 'source': {'ip_address': 'ip_address_value', 'port': 453, 'instance': 'instance_value', 'forwarding_rule': 'forwarding_rule_value', 'forwarding_rule_target': 1, 'load_balancer_id': 'load_balancer_id_value', 'load_balancer_type': 1, 'gke_master_cluster': 'gke_master_cluster_value', 'fqdn': 'fqdn_value', 'cloud_sql_instance': 'cloud_sql_instance_value', 'redis_instance': 'redis_instance_value', 'redis_cluster': 'redis_cluster_value', 'cloud_function': {'uri': 'uri_value'}, 'app_engine_version': {'uri': 'uri_value'}, 'cloud_run_revision': {'uri': 'uri_value'}, 'network': 'network_value', 'network_type': 1, 'project_id': 'project_id_value'}, 'destination': {}, 'protocol': 'protocol_value', 'related_projects': ['related_projects_value1', 'related_projects_value2'], 'display_name': 'display_name_value', 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'reachability_details': {'result': 1, 'verify_time': {}, 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'traces': [{'endpoint_info': {'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'protocol': 'protocol_value', 'source_port': 1205, 'destination_port': 1734, 'source_network_uri': 'source_network_uri_value', 'destination_network_uri': 'destination_network_uri_value', 'source_agent_uri': 'source_agent_uri_value'}, 'steps': [{'description': 'description_value', 'state': 1, 'causes_drop': True, 'project_id': 'project_id_value', 'instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'interface': 'interface_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'network_tags': ['network_tags_value1', 'network_tags_value2'], 'service_account': 'service_account_value', 'psc_network_attachment_uri': 'psc_network_attachment_uri_value'}, 'firewall': {'display_name': 'display_name_value', 'uri': 'uri_value', 'direction': 'direction_value', 'action': 'action_value', 'priority': 898, 'network_uri': 'network_uri_value', 'target_tags': ['target_tags_value1', 'target_tags_value2'], 'target_service_accounts': ['target_service_accounts_value1', 'target_service_accounts_value2'], 'policy': 'policy_value', 'policy_uri': 'policy_uri_value', 'firewall_rule_type': 1}, 'route': {'route_type': 1, 'next_hop_type': 1, 'route_scope': 1, 'display_name': 'display_name_value', 'uri': 'uri_value', 'region': 'region_value', 'dest_ip_range': 'dest_ip_range_value', 'next_hop': 'next_hop_value', 'network_uri': 'network_uri_value', 'priority': 898, 'instance_tags': ['instance_tags_value1', 'instance_tags_value2'], 'src_ip_range': 'src_ip_range_value', 'dest_port_ranges': ['dest_port_ranges_value1', 'dest_port_ranges_value2'], 'src_port_ranges': ['src_port_ranges_value1', 'src_port_ranges_value2'], 'protocols': ['protocols_value1', 'protocols_value2'], 'ncc_hub_uri': 'ncc_hub_uri_value', 'ncc_spoke_uri': 'ncc_spoke_uri_value', 'advertised_route_source_router_uri': 'advertised_route_source_router_uri_value', 'advertised_route_next_hop_uri': 'advertised_route_next_hop_uri_value'}, 'endpoint': {}, 'google_service': {'source_ip': 'source_ip_value', 'google_service_type': 1}, 'forwarding_rule': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_protocol': 'matched_protocol_value', 'matched_port_range': 'matched_port_range_value', 'vip': 'vip_value', 'target': 'target_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'load_balancer_name': 'load_balancer_name_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'vpn_gateway': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'ip_address': 'ip_address_value', 'vpn_tunnel_uri': 'vpn_tunnel_uri_value', 'region': 'region_value'}, 'vpn_tunnel': {'display_name': 'display_name_value', 'uri': 'uri_value', 'source_gateway': 'source_gateway_value', 'remote_gateway': 'remote_gateway_value', 'remote_gateway_ip': 'remote_gateway_ip_value', 'source_gateway_ip': 'source_gateway_ip_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'routing_type': 1}, 'vpc_connector': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value'}, 'deliver': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'storage_bucket': 'storage_bucket_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'forward': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value'}, 'abort': {'cause': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'projects_missing_permission': ['projects_missing_permission_value1', 'projects_missing_permission_value2']}, 'drop': {'cause': 1, 'resource_uri': 'resource_uri_value', 'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'region': 'region_value'}, 'load_balancer': {'load_balancer_type': 1, 'health_check_uri': 'health_check_uri_value', 'backends': [{'display_name': 'display_name_value', 'uri': 'uri_value', 'health_check_firewall_state': 1, 'health_check_allowing_firewall_rules': ['health_check_allowing_firewall_rules_value1', 'health_check_allowing_firewall_rules_value2'], 'health_check_blocking_firewall_rules': ['health_check_blocking_firewall_rules_value1', 'health_check_blocking_firewall_rules_value2']}], 'backend_type': 1, 'backend_uri': 'backend_uri_value'}, 'network': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_subnet_uri': 'matched_subnet_uri_value', 'matched_ip_range': 'matched_ip_range_value', 'region': 'region_value'}, 'gke_master': {'cluster_uri': 'cluster_uri_value', 'cluster_network_uri': 'cluster_network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'dns_endpoint': 'dns_endpoint_value'}, 'cloud_sql_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'region': 'region_value'}, 'redis_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'primary_endpoint_ip': 'primary_endpoint_ip_value', 'read_endpoint_ip': 'read_endpoint_ip_value', 'region': 'region_value'}, 'redis_cluster': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'discovery_endpoint_ip_address': 'discovery_endpoint_ip_address_value', 'secondary_endpoint_ip_address': 'secondary_endpoint_ip_address_value', 'location': 'location_value'}, 'cloud_function': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'version_id': 1074}, 'app_engine_version': {'display_name': 'display_name_value', 'uri': 'uri_value', 'runtime': 'runtime_value', 'environment': 'environment_value'}, 'cloud_run_revision': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'service_uri': 'service_uri_value'}, 'nat': {'type_': 1, 'protocol': 'protocol_value', 'network_uri': 'network_uri_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'router_uri': 'router_uri_value', 'nat_gateway_name': 'nat_gateway_name_value'}, 'proxy_connection': {'protocol': 'protocol_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'subnet_uri': 'subnet_uri_value', 'network_uri': 'network_uri_value'}, 'load_balancer_backend_info': {'name': 'name_value', 'instance_uri': 'instance_uri_value', 'backend_service_uri': 'backend_service_uri_value', 'instance_group_uri': 'instance_group_uri_value', 'network_endpoint_group_uri': 'network_endpoint_group_uri_value', 'backend_bucket_uri': 'backend_bucket_uri_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value', 'health_check_uri': 'health_check_uri_value', 'health_check_firewalls_config_state': 1}, 'storage_bucket': {'bucket': 'bucket_value'}, 'serverless_neg': {'neg_uri': 'neg_uri_value'}}], 'forward_trace_id': 1679}]}, 'probing_details': {'result': 1, 'verify_time': {}, 'error': {}, 'abort_cause': 1, 'sent_probe_count': 1721, 'successful_probe_count': 2367, 'endpoint_info': {}, 'probing_latency': {'latency_percentiles': [{'percent': 753, 'latency_micros': 1500}]}, 'destination_egress_location': {'metropolitan_area': 'metropolitan_area_value'}}, 'round_trip': True, 'return_reachability_details': {}, 'bypass_firewall_checks': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = reachability.UpdateConnectivityTestRequest.meta.fields["resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_update_connectivity_test") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_update_connectivity_test") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.UpdateConnectivityTestRequest.pb(reachability.UpdateConnectivityTestRequest()) + 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 = reachability.UpdateConnectivityTestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_rerun_connectivity_test_rest_bad_request(request_type=reachability.RerunConnectivityTestRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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.rerun_connectivity_test(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.RerunConnectivityTestRequest, + dict, +]) +def test_rerun_connectivity_test_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # 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.rerun_connectivity_test(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_rerun_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_rerun_connectivity_test") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_rerun_connectivity_test") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.RerunConnectivityTestRequest.pb(reachability.RerunConnectivityTestRequest()) + 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 = reachability.RerunConnectivityTestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.rerun_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_connectivity_test_rest_bad_request(request_type=reachability.DeleteConnectivityTestRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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.delete_connectivity_test(request) + + +@pytest.mark.parametrize("request_type", [ + reachability.DeleteConnectivityTestRequest, + dict, +]) +def test_delete_connectivity_test_rest_call_success(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/global/connectivityTests/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_delete_connectivity_test") as post, \ + mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_delete_connectivity_test") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.DeleteConnectivityTestRequest.pb(reachability.DeleteConnectivityTestRequest()) + 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 = reachability.DeleteConnectivityTestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_connectivity_test(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 = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + 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_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/global'}, 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/global'} + 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 = ReachabilityServiceClient( + 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_connectivity_tests_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_connectivity_tests), + '__call__') as call: + client.list_connectivity_tests(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.ListConnectivityTestsRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_connectivity_test), + '__call__') as call: + client.get_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.GetConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_connectivity_test), + '__call__') as call: + client.create_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.CreateConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_connectivity_test), + '__call__') as call: + client.update_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.UpdateConnectivityTestRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rerun_connectivity_test_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rerun_connectivity_test), + '__call__') as call: + client.rerun_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.RerunConnectivityTestRequest() + + assert args[0] == request_msg + + +# This 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_connectivity_test_empty_call_rest(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_connectivity_test), + '__call__') as call: + client.delete_connectivity_test(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reachability.DeleteConnectivityTestRequest() + + assert args[0] == request_msg + + +def test_reachability_service_rest_lro_client(): + client = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ReachabilityServiceGrpcTransport, + ) + +def test_reachability_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ReachabilityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_reachability_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ReachabilityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_connectivity_tests', + 'get_connectivity_test', + 'create_connectivity_test', + 'update_connectivity_test', + 'rerun_connectivity_test', + 'delete_connectivity_test', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_reachability_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReachabilityServiceTransport( + 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_reachability_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReachabilityServiceTransport() + adc.assert_called_once() + + +def test_reachability_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ReachabilityServiceClient() + 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.ReachabilityServiceGrpcTransport, + transports.ReachabilityServiceGrpcAsyncIOTransport, + ], +) +def test_reachability_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ReachabilityServiceGrpcTransport, + transports.ReachabilityServiceGrpcAsyncIOTransport, + transports.ReachabilityServiceRestTransport, + ], +) +def test_reachability_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ReachabilityServiceGrpcTransport, grpc_helpers), + (transports.ReachabilityServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_reachability_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "networkmanagement.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="networkmanagement.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) +def test_reachability_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_reachability_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ReachabilityServiceRestTransport ( + 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_reachability_service_host_no_port(transport_name): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networkmanagement.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networkmanagement.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networkmanagement.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_reachability_service_host_with_port(transport_name): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networkmanagement.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networkmanagement.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networkmanagement.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_reachability_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ReachabilityServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ReachabilityServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_connectivity_tests._session + session2 = client2.transport.list_connectivity_tests._session + assert session1 != session2 + session1 = client1.transport.get_connectivity_test._session + session2 = client2.transport.get_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.create_connectivity_test._session + session2 = client2.transport.create_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.update_connectivity_test._session + session2 = client2.transport.update_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.rerun_connectivity_test._session + session2 = client2.transport.rerun_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.delete_connectivity_test._session + session2 = client2.transport.delete_connectivity_test._session + assert session1 != session2 +def test_reachability_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ReachabilityServiceGrpcTransport( + 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_reachability_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ReachabilityServiceGrpcAsyncIOTransport( + 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.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) +def test_reachability_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) +def test_reachability_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_reachability_service_grpc_lro_client(): + client = ReachabilityServiceClient( + 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_reachability_service_grpc_lro_async_client(): + client = ReachabilityServiceAsyncClient( + 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_connectivity_test_path(): + project = "squid" + test = "clam" + expected = "projects/{project}/locations/global/connectivityTests/{test}".format(project=project, test=test, ) + actual = ReachabilityServiceClient.connectivity_test_path(project, test) + assert expected == actual + + +def test_parse_connectivity_test_path(): + expected = { + "project": "whelk", + "test": "octopus", + } + path = ReachabilityServiceClient.connectivity_test_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.parse_connectivity_test_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ReachabilityServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ReachabilityServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ReachabilityServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ReachabilityServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ReachabilityServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ReachabilityServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ReachabilityServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ReachabilityServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ReachabilityServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ReachabilityServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ReachabilityServiceClient.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.ReachabilityServiceTransport, '_prep_wrapped_messages') as prep: + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ReachabilityServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ReachabilityServiceClient.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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = ReachabilityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = ReachabilityServiceClient( + 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 = ReachabilityServiceAsyncClient( + 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 = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + 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", [ + (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport), + (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From fcbf879909a36a416a8916a04970e8d486db5815 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 14 Nov 2024 09:08:33 +0000 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../v1/.coveragerc | 13 - .../v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../reachability_service.rst | 10 - .../docs/network_management_v1/services_.rst | 6 - .../v1/docs/network_management_v1/types_.rst | 6 - .../cloud/network_management/__init__.py | 117 - .../cloud/network_management/gapic_version.py | 16 - .../google/cloud/network_management/py.typed | 2 - .../cloud/network_management_v1/__init__.py | 118 - .../network_management_v1/gapic_metadata.json | 118 - .../network_management_v1/gapic_version.py | 16 - .../cloud/network_management_v1/py.typed | 2 - .../services/__init__.py | 15 - .../services/reachability_service/__init__.py | 22 - .../reachability_service/async_client.py | 1597 ---- .../services/reachability_service/client.py | 1917 ----- .../services/reachability_service/pagers.py | 163 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../reachability_service/transports/base.py | 362 - .../reachability_service/transports/grpc.py | 660 -- .../transports/grpc_asyncio.py | 751 -- .../reachability_service/transports/rest.py | 1714 ---- .../transports/rest_base.py | 588 -- .../network_management_v1/types/__init__.py | 114 - .../types/connectivity_test.py | 753 -- .../types/reachability.py | 293 - .../network_management_v1/types/trace.py | 3164 ------- .../v1/mypy.ini | 3 - .../v1/noxfile.py | 280 - ..._service_create_connectivity_test_async.py | 57 - ...y_service_create_connectivity_test_sync.py | 57 - ..._service_delete_connectivity_test_async.py | 56 - ...y_service_delete_connectivity_test_sync.py | 56 - ...ity_service_get_connectivity_test_async.py | 52 - ...lity_service_get_connectivity_test_sync.py | 52 - ...y_service_list_connectivity_tests_async.py | 53 - ...ty_service_list_connectivity_tests_sync.py | 53 - ...y_service_rerun_connectivity_test_async.py | 56 - ...ty_service_rerun_connectivity_test_sync.py | 56 - ..._service_update_connectivity_test_async.py | 55 - ...y_service_update_connectivity_test_sync.py | 55 - ...ata_google.cloud.networkmanagement.v1.json | 997 --- .../fixup_network_management_v1_keywords.py | 181 - .../v1/setup.py | 99 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.13.txt | 7 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/network_management_v1/__init__.py | 16 - .../test_reachability_service.py | 7469 ----------------- .../types/connectivity_test.py | 18 + .../test_reachability_service.py | 11 + 64 files changed, 29 insertions(+), 22858 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/.coveragerc b/owl-bot-staging/google-cloud-network-management/v1/.coveragerc deleted file mode 100644 index 20f78aac3034..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/network_management/__init__.py - google/cloud/network_management/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-network-management/v1/.flake8 b/owl-bot-staging/google-cloud-network-management/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in b/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in deleted file mode 100644 index 240002b7c5c7..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/network_management *.py -recursive-include google/cloud/network_management_v1 *.py diff --git a/owl-bot-staging/google-cloud-network-management/v1/README.rst b/owl-bot-staging/google-cloud-network-management/v1/README.rst deleted file mode 100644 index 264724cca11b..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Network Management 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 Network Management 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-network-management/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py b/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py deleted file mode 100644 index a303b54b23a8..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-network-management documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-network-management" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-network-management-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-network-management.tex", - u"google-cloud-network-management Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-network-management", - u"Google Cloud Network Management 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-network-management", - u"google-cloud-network-management Documentation", - author, - "google-cloud-network-management", - "GAPIC library for Google Cloud Network Management 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-network-management/v1/docs/index.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/index.rst deleted file mode 100644 index df608d7805a8..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - network_management_v1/services_ - network_management_v1/types_ diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst deleted file mode 100644 index 1d3502a632c9..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/reachability_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ReachabilityService -------------------------------------- - -.. automodule:: google.cloud.network_management_v1.services.reachability_service - :members: - :inherited-members: - -.. automodule:: google.cloud.network_management_v1.services.reachability_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst deleted file mode 100644 index e26ca50e5fc4..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Network Management v1 API -=================================================== -.. toctree:: - :maxdepth: 2 - - reachability_service diff --git a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst b/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst deleted file mode 100644 index 11bcca7b4b58..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/docs/network_management_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Network Management v1 API -================================================ - -.. automodule:: google.cloud.network_management_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py deleted file mode 100644 index 23a237dd11fa..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/__init__.py +++ /dev/null @@ -1,117 +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.network_management import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.network_management_v1.services.reachability_service.client import ReachabilityServiceClient -from google.cloud.network_management_v1.services.reachability_service.async_client import ReachabilityServiceAsyncClient - -from google.cloud.network_management_v1.types.connectivity_test import ConnectivityTest -from google.cloud.network_management_v1.types.connectivity_test import Endpoint -from google.cloud.network_management_v1.types.connectivity_test import LatencyDistribution -from google.cloud.network_management_v1.types.connectivity_test import LatencyPercentile -from google.cloud.network_management_v1.types.connectivity_test import ProbingDetails -from google.cloud.network_management_v1.types.connectivity_test import ReachabilityDetails -from google.cloud.network_management_v1.types.reachability import CreateConnectivityTestRequest -from google.cloud.network_management_v1.types.reachability import DeleteConnectivityTestRequest -from google.cloud.network_management_v1.types.reachability import GetConnectivityTestRequest -from google.cloud.network_management_v1.types.reachability import ListConnectivityTestsRequest -from google.cloud.network_management_v1.types.reachability import ListConnectivityTestsResponse -from google.cloud.network_management_v1.types.reachability import OperationMetadata -from google.cloud.network_management_v1.types.reachability import RerunConnectivityTestRequest -from google.cloud.network_management_v1.types.reachability import UpdateConnectivityTestRequest -from google.cloud.network_management_v1.types.trace import AbortInfo -from google.cloud.network_management_v1.types.trace import AppEngineVersionInfo -from google.cloud.network_management_v1.types.trace import CloudFunctionInfo -from google.cloud.network_management_v1.types.trace import CloudRunRevisionInfo -from google.cloud.network_management_v1.types.trace import CloudSQLInstanceInfo -from google.cloud.network_management_v1.types.trace import DeliverInfo -from google.cloud.network_management_v1.types.trace import DropInfo -from google.cloud.network_management_v1.types.trace import EndpointInfo -from google.cloud.network_management_v1.types.trace import FirewallInfo -from google.cloud.network_management_v1.types.trace import ForwardInfo -from google.cloud.network_management_v1.types.trace import ForwardingRuleInfo -from google.cloud.network_management_v1.types.trace import GKEMasterInfo -from google.cloud.network_management_v1.types.trace import GoogleServiceInfo -from google.cloud.network_management_v1.types.trace import InstanceInfo -from google.cloud.network_management_v1.types.trace import LoadBalancerBackend -from google.cloud.network_management_v1.types.trace import LoadBalancerBackendInfo -from google.cloud.network_management_v1.types.trace import LoadBalancerInfo -from google.cloud.network_management_v1.types.trace import NatInfo -from google.cloud.network_management_v1.types.trace import NetworkInfo -from google.cloud.network_management_v1.types.trace import ProxyConnectionInfo -from google.cloud.network_management_v1.types.trace import RedisClusterInfo -from google.cloud.network_management_v1.types.trace import RedisInstanceInfo -from google.cloud.network_management_v1.types.trace import RouteInfo -from google.cloud.network_management_v1.types.trace import ServerlessNegInfo -from google.cloud.network_management_v1.types.trace import Step -from google.cloud.network_management_v1.types.trace import StorageBucketInfo -from google.cloud.network_management_v1.types.trace import Trace -from google.cloud.network_management_v1.types.trace import VpcConnectorInfo -from google.cloud.network_management_v1.types.trace import VpnGatewayInfo -from google.cloud.network_management_v1.types.trace import VpnTunnelInfo -from google.cloud.network_management_v1.types.trace import LoadBalancerType - -__all__ = ('ReachabilityServiceClient', - 'ReachabilityServiceAsyncClient', - 'ConnectivityTest', - 'Endpoint', - 'LatencyDistribution', - 'LatencyPercentile', - 'ProbingDetails', - 'ReachabilityDetails', - 'CreateConnectivityTestRequest', - 'DeleteConnectivityTestRequest', - 'GetConnectivityTestRequest', - 'ListConnectivityTestsRequest', - 'ListConnectivityTestsResponse', - 'OperationMetadata', - 'RerunConnectivityTestRequest', - 'UpdateConnectivityTestRequest', - 'AbortInfo', - 'AppEngineVersionInfo', - 'CloudFunctionInfo', - 'CloudRunRevisionInfo', - 'CloudSQLInstanceInfo', - 'DeliverInfo', - 'DropInfo', - 'EndpointInfo', - 'FirewallInfo', - 'ForwardInfo', - 'ForwardingRuleInfo', - 'GKEMasterInfo', - 'GoogleServiceInfo', - 'InstanceInfo', - 'LoadBalancerBackend', - 'LoadBalancerBackendInfo', - 'LoadBalancerInfo', - 'NatInfo', - 'NetworkInfo', - 'ProxyConnectionInfo', - 'RedisClusterInfo', - 'RedisInstanceInfo', - 'RouteInfo', - 'ServerlessNegInfo', - 'Step', - 'StorageBucketInfo', - 'Trace', - 'VpcConnectorInfo', - 'VpnGatewayInfo', - 'VpnTunnelInfo', - 'LoadBalancerType', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/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-network-management/v1/google/cloud/network_management/py.typed b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed deleted file mode 100644 index 5aa063ef7ba9..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-management package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py deleted file mode 100644 index a55edfec563a..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/__init__.py +++ /dev/null @@ -1,118 +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.network_management_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.reachability_service import ReachabilityServiceClient -from .services.reachability_service import ReachabilityServiceAsyncClient - -from .types.connectivity_test import ConnectivityTest -from .types.connectivity_test import Endpoint -from .types.connectivity_test import LatencyDistribution -from .types.connectivity_test import LatencyPercentile -from .types.connectivity_test import ProbingDetails -from .types.connectivity_test import ReachabilityDetails -from .types.reachability import CreateConnectivityTestRequest -from .types.reachability import DeleteConnectivityTestRequest -from .types.reachability import GetConnectivityTestRequest -from .types.reachability import ListConnectivityTestsRequest -from .types.reachability import ListConnectivityTestsResponse -from .types.reachability import OperationMetadata -from .types.reachability import RerunConnectivityTestRequest -from .types.reachability import UpdateConnectivityTestRequest -from .types.trace import AbortInfo -from .types.trace import AppEngineVersionInfo -from .types.trace import CloudFunctionInfo -from .types.trace import CloudRunRevisionInfo -from .types.trace import CloudSQLInstanceInfo -from .types.trace import DeliverInfo -from .types.trace import DropInfo -from .types.trace import EndpointInfo -from .types.trace import FirewallInfo -from .types.trace import ForwardInfo -from .types.trace import ForwardingRuleInfo -from .types.trace import GKEMasterInfo -from .types.trace import GoogleServiceInfo -from .types.trace import InstanceInfo -from .types.trace import LoadBalancerBackend -from .types.trace import LoadBalancerBackendInfo -from .types.trace import LoadBalancerInfo -from .types.trace import NatInfo -from .types.trace import NetworkInfo -from .types.trace import ProxyConnectionInfo -from .types.trace import RedisClusterInfo -from .types.trace import RedisInstanceInfo -from .types.trace import RouteInfo -from .types.trace import ServerlessNegInfo -from .types.trace import Step -from .types.trace import StorageBucketInfo -from .types.trace import Trace -from .types.trace import VpcConnectorInfo -from .types.trace import VpnGatewayInfo -from .types.trace import VpnTunnelInfo -from .types.trace import LoadBalancerType - -__all__ = ( - 'ReachabilityServiceAsyncClient', -'AbortInfo', -'AppEngineVersionInfo', -'CloudFunctionInfo', -'CloudRunRevisionInfo', -'CloudSQLInstanceInfo', -'ConnectivityTest', -'CreateConnectivityTestRequest', -'DeleteConnectivityTestRequest', -'DeliverInfo', -'DropInfo', -'Endpoint', -'EndpointInfo', -'FirewallInfo', -'ForwardInfo', -'ForwardingRuleInfo', -'GKEMasterInfo', -'GetConnectivityTestRequest', -'GoogleServiceInfo', -'InstanceInfo', -'LatencyDistribution', -'LatencyPercentile', -'ListConnectivityTestsRequest', -'ListConnectivityTestsResponse', -'LoadBalancerBackend', -'LoadBalancerBackendInfo', -'LoadBalancerInfo', -'LoadBalancerType', -'NatInfo', -'NetworkInfo', -'OperationMetadata', -'ProbingDetails', -'ProxyConnectionInfo', -'ReachabilityDetails', -'ReachabilityServiceClient', -'RedisClusterInfo', -'RedisInstanceInfo', -'RerunConnectivityTestRequest', -'RouteInfo', -'ServerlessNegInfo', -'Step', -'StorageBucketInfo', -'Trace', -'UpdateConnectivityTestRequest', -'VpcConnectorInfo', -'VpnGatewayInfo', -'VpnTunnelInfo', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json deleted file mode 100644 index 6c5315440fef..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_metadata.json +++ /dev/null @@ -1,118 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.network_management_v1", - "protoPackage": "google.cloud.networkmanagement.v1", - "schema": "1.0", - "services": { - "ReachabilityService": { - "clients": { - "grpc": { - "libraryClient": "ReachabilityServiceClient", - "rpcs": { - "CreateConnectivityTest": { - "methods": [ - "create_connectivity_test" - ] - }, - "DeleteConnectivityTest": { - "methods": [ - "delete_connectivity_test" - ] - }, - "GetConnectivityTest": { - "methods": [ - "get_connectivity_test" - ] - }, - "ListConnectivityTests": { - "methods": [ - "list_connectivity_tests" - ] - }, - "RerunConnectivityTest": { - "methods": [ - "rerun_connectivity_test" - ] - }, - "UpdateConnectivityTest": { - "methods": [ - "update_connectivity_test" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ReachabilityServiceAsyncClient", - "rpcs": { - "CreateConnectivityTest": { - "methods": [ - "create_connectivity_test" - ] - }, - "DeleteConnectivityTest": { - "methods": [ - "delete_connectivity_test" - ] - }, - "GetConnectivityTest": { - "methods": [ - "get_connectivity_test" - ] - }, - "ListConnectivityTests": { - "methods": [ - "list_connectivity_tests" - ] - }, - "RerunConnectivityTest": { - "methods": [ - "rerun_connectivity_test" - ] - }, - "UpdateConnectivityTest": { - "methods": [ - "update_connectivity_test" - ] - } - } - }, - "rest": { - "libraryClient": "ReachabilityServiceClient", - "rpcs": { - "CreateConnectivityTest": { - "methods": [ - "create_connectivity_test" - ] - }, - "DeleteConnectivityTest": { - "methods": [ - "delete_connectivity_test" - ] - }, - "GetConnectivityTest": { - "methods": [ - "get_connectivity_test" - ] - }, - "ListConnectivityTests": { - "methods": [ - "list_connectivity_tests" - ] - }, - "RerunConnectivityTest": { - "methods": [ - "rerun_connectivity_test" - ] - }, - "UpdateConnectivityTest": { - "methods": [ - "update_connectivity_test" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_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-network-management/v1/google/cloud/network_management_v1/py.typed b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed deleted file mode 100644 index 5aa063ef7ba9..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-management package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_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-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__init__.py deleted file mode 100644 index 6f536eeb4ca5..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/__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 ReachabilityServiceClient -from .async_client import ReachabilityServiceAsyncClient - -__all__ = ( - 'ReachabilityServiceClient', - 'ReachabilityServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py deleted file mode 100644 index 0ae89e6c03d8..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/async_client.py +++ /dev/null @@ -1,1597 +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.network_management_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.location import locations_pb2 # type: ignore -from google.cloud.network_management_v1.services.reachability_service import pagers -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport -from .client import ReachabilityServiceClient - - -class ReachabilityServiceAsyncClient: - """The Reachability service in the Google Cloud Network - Management API provides services that analyze the reachability - within a single Google Virtual Private Cloud (VPC) network, - between peered VPC networks, between VPC and on-premises - networks, or between VPC networks and internet hosts. A - reachability analysis is based on Google Cloud network - configurations. - - You can use the analysis results to verify these configurations - and to troubleshoot connectivity issues. - """ - - _client: ReachabilityServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ReachabilityServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ReachabilityServiceClient._DEFAULT_UNIVERSE - - connectivity_test_path = staticmethod(ReachabilityServiceClient.connectivity_test_path) - parse_connectivity_test_path = staticmethod(ReachabilityServiceClient.parse_connectivity_test_path) - common_billing_account_path = staticmethod(ReachabilityServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ReachabilityServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ReachabilityServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ReachabilityServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ReachabilityServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ReachabilityServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ReachabilityServiceClient.common_project_path) - parse_common_project_path = staticmethod(ReachabilityServiceClient.parse_common_project_path) - common_location_path = staticmethod(ReachabilityServiceClient.common_location_path) - parse_common_location_path = staticmethod(ReachabilityServiceClient.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: - ReachabilityServiceAsyncClient: The constructed client. - """ - return ReachabilityServiceClient.from_service_account_info.__func__(ReachabilityServiceAsyncClient, 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: - ReachabilityServiceAsyncClient: The constructed client. - """ - return ReachabilityServiceClient.from_service_account_file.__func__(ReachabilityServiceAsyncClient, 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 ReachabilityServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ReachabilityServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ReachabilityServiceTransport: 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 = ReachabilityServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ReachabilityServiceTransport, Callable[..., ReachabilityServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the reachability service async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,ReachabilityServiceTransport,Callable[..., ReachabilityServiceTransport]]]): - 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 ReachabilityServiceTransport 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 = ReachabilityServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_connectivity_tests(self, - request: Optional[Union[reachability.ListConnectivityTestsRequest, 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.ListConnectivityTestsAsyncPager: - r"""Lists all Connectivity Tests owned by a project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_list_connectivity_tests(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.ListConnectivityTestsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_connectivity_tests(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.ListConnectivityTestsRequest, dict]]): - The request object. Request for the ``ListConnectivityTests`` method. - parent (:class:`str`): - Required. The parent resource of the Connectivity Tests: - ``projects/{project_id}/locations/global`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsAsyncPager: - Response for the ListConnectivityTests method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, reachability.ListConnectivityTestsRequest): - request = reachability.ListConnectivityTestsRequest(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_connectivity_tests] - - # 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.ListConnectivityTestsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_connectivity_test(self, - request: Optional[Union[reachability.GetConnectivityTestRequest, 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]] = (), - ) -> connectivity_test.ConnectivityTest: - r"""Gets the details of a specific Connectivity Test. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_get_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.GetConnectivityTestRequest( - name="name_value", - ) - - # Make the request - response = await client.get_connectivity_test(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.GetConnectivityTestRequest, dict]]): - The request object. Request for the ``GetConnectivityTest`` method. - name (:class:`str`): - Required. ``ConnectivityTest`` resource name using the - form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - - 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.network_management_v1.types.ConnectivityTest: - A Connectivity Test for a network - reachability analysis. - - """ - # Create or coerce a 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, reachability.GetConnectivityTestRequest): - request = reachability.GetConnectivityTestRequest(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_connectivity_test] - - # 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_connectivity_test(self, - request: Optional[Union[reachability.CreateConnectivityTestRequest, dict]] = None, - *, - parent: Optional[str] = None, - test_id: Optional[str] = None, - resource: Optional[connectivity_test.ConnectivityTest] = 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 Connectivity Test. After you create a test, the - reachability analysis is performed as part of the long running - operation, which completes when the analysis completes. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, containing non-existent resources in the - network, or you don't have read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - AMBIGUOUS. For more information, see the Connectivity Test - documentation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_create_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.CreateConnectivityTestRequest( - parent="parent_value", - test_id="test_id_value", - ) - - # Make the request - operation = client.create_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.CreateConnectivityTestRequest, dict]]): - The request object. Request for the ``CreateConnectivityTest`` method. - parent (:class:`str`): - Required. The parent resource of the Connectivity Test - to create: ``projects/{project_id}/locations/global`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - test_id (:class:`str`): - Required. The logical name of the Connectivity Test in - your project with the following restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-40 characters. - - Must end with a number or a letter. - - Must be unique within the customer project - - This corresponds to the ``test_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (:class:`google.cloud.network_management_v1.types.ConnectivityTest`): - Required. A ``ConnectivityTest`` resource - This corresponds to the ``resource`` 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.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a 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, test_id, resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.CreateConnectivityTestRequest): - request = reachability.CreateConnectivityTestRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if test_id is not None: - request.test_id = test_id - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_connectivity_test] - - # 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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_connectivity_test(self, - request: Optional[Union[reachability.UpdateConnectivityTestRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - resource: Optional[connectivity_test.ConnectivityTest] = 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 configuration of an existing ``ConnectivityTest``. - After you update a test, the reachability analysis is performed - as part of the long running operation, which completes when the - analysis completes. The Reachability state in the test resource - is updated with the new result. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, they contain non-existent resources in the - network, or the user does not have read permissions to the - network configurations of listed projects), then the - reachability result returns a value of UNKNOWN. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for - more details. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_update_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.UpdateConnectivityTestRequest( - ) - - # Make the request - operation = client.update_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.UpdateConnectivityTestRequest, dict]]): - The request object. Request for the ``UpdateConnectivityTest`` method. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask of fields to update. - At least one path must be supplied in - this field. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (:class:`google.cloud.network_management_v1.types.ConnectivityTest`): - Required. Only fields specified in update_mask are - updated. - - This corresponds to the ``resource`` 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.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a 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([update_mask, resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.UpdateConnectivityTestRequest): - request = reachability.UpdateConnectivityTestRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if update_mask is not None: - request.update_mask = update_mask - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_connectivity_test] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource.name", request.resource.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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - async def rerun_connectivity_test(self, - request: Optional[Union[reachability.RerunConnectivityTestRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Rerun an existing ``ConnectivityTest``. After the user triggers - the rerun, the reachability analysis is performed as part of the - long running operation, which completes when the analysis - completes. - - Even though the test configuration remains the same, the - reachability result may change due to underlying network - configuration changes. - - If the endpoint specifications in ``ConnectivityTest`` become - invalid (for example, specified resources are deleted in the - network, or you lost read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_rerun_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.RerunConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.rerun_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.RerunConnectivityTestRequest, dict]]): - The request object. Request for the ``RerunConnectivityTest`` 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: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.RerunConnectivityTestRequest): - request = reachability.RerunConnectivityTestRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.rerun_connectivity_test] - - # 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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_connectivity_test(self, - request: Optional[Union[reachability.DeleteConnectivityTestRequest, 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 specific ``ConnectivityTest``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - async def sample_delete_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.DeleteConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_management_v1.types.DeleteConnectivityTestRequest, dict]]): - The request object. Request for the ``DeleteConnectivityTest`` method. - name (:class:`str`): - Required. Connectivity Test resource name using the - form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - - 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, reachability.DeleteConnectivityTestRequest): - request = reachability.DeleteConnectivityTestRequest(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_connectivity_test] - - # 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=reachability.OperationMetadata, - ) - - # 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, 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) -> "ReachabilityServiceAsyncClient": - 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__ = ( - "ReachabilityServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py deleted file mode 100644 index af1f94e73757..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/client.py +++ /dev/null @@ -1,1917 +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.network_management_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.location import locations_pb2 # type: ignore -from google.cloud.network_management_v1.services.reachability_service import pagers -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ReachabilityServiceGrpcTransport -from .transports.grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport -from .transports.rest import ReachabilityServiceRestTransport - - -class ReachabilityServiceClientMeta(type): - """Metaclass for the ReachabilityService 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[ReachabilityServiceTransport]] - _transport_registry["grpc"] = ReachabilityServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ReachabilityServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ReachabilityServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ReachabilityServiceTransport]: - """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 ReachabilityServiceClient(metaclass=ReachabilityServiceClientMeta): - """The Reachability service in the Google Cloud Network - Management API provides services that analyze the reachability - within a single Google Virtual Private Cloud (VPC) network, - between peered VPC networks, between VPC and on-premises - networks, or between VPC networks and internet hosts. A - reachability analysis is based on Google Cloud network - configurations. - - You can use the analysis results to verify these configurations - and to troubleshoot connectivity issues. - """ - - @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 = "networkmanagement.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "networkmanagement.{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: - ReachabilityServiceClient: 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: - ReachabilityServiceClient: 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) -> ReachabilityServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ReachabilityServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def connectivity_test_path(project: str,test: str,) -> str: - """Returns a fully-qualified connectivity_test string.""" - return "projects/{project}/locations/global/connectivityTests/{test}".format(project=project, test=test, ) - - @staticmethod - def parse_connectivity_test_path(path: str) -> Dict[str,str]: - """Parses a connectivity_test path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/global/connectivityTests/(?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 = ReachabilityServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ReachabilityServiceClient._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 = ReachabilityServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ReachabilityServiceTransport, Callable[..., ReachabilityServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the reachability service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,ReachabilityServiceTransport,Callable[..., ReachabilityServiceTransport]]]): - 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 ReachabilityServiceTransport 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 = ReachabilityServiceClient._read_environment_variables() - self._client_cert_source = ReachabilityServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ReachabilityServiceClient._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, ReachabilityServiceTransport) - if transport_provided: - # transport is a ReachabilityServiceTransport 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(ReachabilityServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ReachabilityServiceClient._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[ReachabilityServiceTransport], Callable[..., ReachabilityServiceTransport]] = ( - ReachabilityServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ReachabilityServiceTransport], 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_connectivity_tests(self, - request: Optional[Union[reachability.ListConnectivityTestsRequest, 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.ListConnectivityTestsPager: - r"""Lists all Connectivity Tests owned by a project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_list_connectivity_tests(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.ListConnectivityTestsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_connectivity_tests(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.ListConnectivityTestsRequest, dict]): - The request object. Request for the ``ListConnectivityTests`` method. - parent (str): - Required. The parent resource of the Connectivity Tests: - ``projects/{project_id}/locations/global`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsPager: - Response for the ListConnectivityTests method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, reachability.ListConnectivityTestsRequest): - request = reachability.ListConnectivityTestsRequest(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_connectivity_tests] - - # 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.ListConnectivityTestsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_connectivity_test(self, - request: Optional[Union[reachability.GetConnectivityTestRequest, 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]] = (), - ) -> connectivity_test.ConnectivityTest: - r"""Gets the details of a specific Connectivity Test. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_get_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.GetConnectivityTestRequest( - name="name_value", - ) - - # Make the request - response = client.get_connectivity_test(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.GetConnectivityTestRequest, dict]): - The request object. Request for the ``GetConnectivityTest`` method. - name (str): - Required. ``ConnectivityTest`` resource name using the - form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - - 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.network_management_v1.types.ConnectivityTest: - A Connectivity Test for a network - reachability analysis. - - """ - # Create or coerce a 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, reachability.GetConnectivityTestRequest): - request = reachability.GetConnectivityTestRequest(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_connectivity_test] - - # 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_connectivity_test(self, - request: Optional[Union[reachability.CreateConnectivityTestRequest, dict]] = None, - *, - parent: Optional[str] = None, - test_id: Optional[str] = None, - resource: Optional[connectivity_test.ConnectivityTest] = 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 Connectivity Test. After you create a test, the - reachability analysis is performed as part of the long running - operation, which completes when the analysis completes. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, containing non-existent resources in the - network, or you don't have read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - AMBIGUOUS. For more information, see the Connectivity Test - documentation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_create_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.CreateConnectivityTestRequest( - parent="parent_value", - test_id="test_id_value", - ) - - # Make the request - operation = client.create_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.CreateConnectivityTestRequest, dict]): - The request object. Request for the ``CreateConnectivityTest`` method. - parent (str): - Required. The parent resource of the Connectivity Test - to create: ``projects/{project_id}/locations/global`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - test_id (str): - Required. The logical name of the Connectivity Test in - your project with the following restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-40 characters. - - Must end with a number or a letter. - - Must be unique within the customer project - - This corresponds to the ``test_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (google.cloud.network_management_v1.types.ConnectivityTest): - Required. A ``ConnectivityTest`` resource - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a 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, test_id, resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.CreateConnectivityTestRequest): - request = reachability.CreateConnectivityTestRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if test_id is not None: - request.test_id = test_id - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_connectivity_test] - - # 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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_connectivity_test(self, - request: Optional[Union[reachability.UpdateConnectivityTestRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - resource: Optional[connectivity_test.ConnectivityTest] = 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 configuration of an existing ``ConnectivityTest``. - After you update a test, the reachability analysis is performed - as part of the long running operation, which completes when the - analysis completes. The Reachability state in the test resource - is updated with the new result. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, they contain non-existent resources in the - network, or the user does not have read permissions to the - network configurations of listed projects), then the - reachability result returns a value of UNKNOWN. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for - more details. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_update_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.UpdateConnectivityTestRequest( - ) - - # Make the request - operation = client.update_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.UpdateConnectivityTestRequest, dict]): - The request object. Request for the ``UpdateConnectivityTest`` method. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask of fields to update. - At least one path must be supplied in - this field. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (google.cloud.network_management_v1.types.ConnectivityTest): - Required. Only fields specified in update_mask are - updated. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a 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([update_mask, resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.UpdateConnectivityTestRequest): - request = reachability.UpdateConnectivityTestRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if update_mask is not None: - request.update_mask = update_mask - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_connectivity_test] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource.name", request.resource.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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - def rerun_connectivity_test(self, - request: Optional[Union[reachability.RerunConnectivityTestRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Rerun an existing ``ConnectivityTest``. After the user triggers - the rerun, the reachability analysis is performed as part of the - long running operation, which completes when the analysis - completes. - - Even though the test configuration remains the same, the - reachability result may change due to underlying network - configuration changes. - - If the endpoint specifications in ``ConnectivityTest`` become - invalid (for example, specified resources are deleted in the - network, or you lost read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_rerun_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.RerunConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.rerun_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.RerunConnectivityTestRequest, dict]): - The request object. Request for the ``RerunConnectivityTest`` 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: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.network_management_v1.types.ConnectivityTest` - A Connectivity Test for a network reachability analysis. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reachability.RerunConnectivityTestRequest): - request = reachability.RerunConnectivityTestRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rerun_connectivity_test] - - # 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, - connectivity_test.ConnectivityTest, - metadata_type=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_connectivity_test(self, - request: Optional[Union[reachability.DeleteConnectivityTestRequest, 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 specific ``ConnectivityTest``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_management_v1 - - def sample_delete_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.DeleteConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_management_v1.types.DeleteConnectivityTestRequest, dict]): - The request object. Request for the ``DeleteConnectivityTest`` method. - name (str): - Required. Connectivity Test resource name using the - form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - - 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, reachability.DeleteConnectivityTestRequest): - request = reachability.DeleteConnectivityTestRequest(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_connectivity_test] - - # 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=reachability.OperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ReachabilityServiceClient": - 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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__ = ( - "ReachabilityServiceClient", -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py deleted file mode 100644 index 99e5a56eabf4..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/pagers.py +++ /dev/null @@ -1,163 +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.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability - - -class ListConnectivityTestsPager: - """A pager for iterating through ``list_connectivity_tests`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``resources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConnectivityTests`` requests and continue to iterate - through the ``resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` - 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[..., reachability.ListConnectivityTestsResponse], - request: reachability.ListConnectivityTestsRequest, - response: reachability.ListConnectivityTestsResponse, - *, - 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.network_management_v1.types.ListConnectivityTestsRequest): - The initial request object. - response (google.cloud.network_management_v1.types.ListConnectivityTestsResponse): - 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 = reachability.ListConnectivityTestsRequest(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[reachability.ListConnectivityTestsResponse]: - 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[connectivity_test.ConnectivityTest]: - for page in self.pages: - yield from page.resources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConnectivityTestsAsyncPager: - """A pager for iterating through ``list_connectivity_tests`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``resources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConnectivityTests`` requests and continue to iterate - through the ``resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_management_v1.types.ListConnectivityTestsResponse` - 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[reachability.ListConnectivityTestsResponse]], - request: reachability.ListConnectivityTestsRequest, - response: reachability.ListConnectivityTestsResponse, - *, - 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.network_management_v1.types.ListConnectivityTestsRequest): - The initial request object. - response (google.cloud.network_management_v1.types.ListConnectivityTestsResponse): - 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 = reachability.ListConnectivityTestsRequest(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[reachability.ListConnectivityTestsResponse]: - 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[connectivity_test.ConnectivityTest]: - async def async_generator(): - async for page in self.pages: - for response in page.resources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst deleted file mode 100644 index b6e73840492e..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ReachabilityServiceTransport` is the ABC for all transports. -- public child `ReachabilityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ReachabilityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseReachabilityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ReachabilityServiceRestTransport` 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-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py deleted file mode 100644 index e03fcb9eb663..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/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 ReachabilityServiceTransport -from .grpc import ReachabilityServiceGrpcTransport -from .grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport -from .rest import ReachabilityServiceRestTransport -from .rest import ReachabilityServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ReachabilityServiceTransport]] -_transport_registry['grpc'] = ReachabilityServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ReachabilityServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ReachabilityServiceRestTransport - -__all__ = ( - 'ReachabilityServiceTransport', - 'ReachabilityServiceGrpcTransport', - 'ReachabilityServiceGrpcAsyncIOTransport', - 'ReachabilityServiceRestTransport', - 'ReachabilityServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py deleted file mode 100644 index 3d64ec294ab6..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/base.py +++ /dev/null @@ -1,362 +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.network_management_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.location import locations_pb2 # type: ignore -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ReachabilityServiceTransport(abc.ABC): - """Abstract transport class for ReachabilityService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'networkmanagement.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: 'networkmanagement.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_connectivity_tests: gapic_v1.method.wrap_method( - self.list_connectivity_tests, - default_timeout=None, - client_info=client_info, - ), - self.get_connectivity_test: gapic_v1.method.wrap_method( - self.get_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.create_connectivity_test: gapic_v1.method.wrap_method( - self.create_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.update_connectivity_test: gapic_v1.method.wrap_method( - self.update_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.rerun_connectivity_test: gapic_v1.method.wrap_method( - self.rerun_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.delete_connectivity_test: gapic_v1.method.wrap_method( - self.delete_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_connectivity_tests(self) -> Callable[ - [reachability.ListConnectivityTestsRequest], - Union[ - reachability.ListConnectivityTestsResponse, - Awaitable[reachability.ListConnectivityTestsResponse] - ]]: - raise NotImplementedError() - - @property - def get_connectivity_test(self) -> Callable[ - [reachability.GetConnectivityTestRequest], - Union[ - connectivity_test.ConnectivityTest, - Awaitable[connectivity_test.ConnectivityTest] - ]]: - raise NotImplementedError() - - @property - def create_connectivity_test(self) -> Callable[ - [reachability.CreateConnectivityTestRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_connectivity_test(self) -> Callable[ - [reachability.UpdateConnectivityTestRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rerun_connectivity_test(self) -> Callable[ - [reachability.RerunConnectivityTestRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_connectivity_test(self) -> Callable[ - [reachability.DeleteConnectivityTestRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ReachabilityServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py deleted file mode 100644 index 04909d6e22c7..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc.py +++ /dev/null @@ -1,660 +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.location import locations_pb2 # type: ignore -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO - - -class ReachabilityServiceGrpcTransport(ReachabilityServiceTransport): - """gRPC backend transport for ReachabilityService. - - The Reachability service in the Google Cloud Network - Management API provides services that analyze the reachability - within a single Google Virtual Private Cloud (VPC) network, - between peered VPC networks, between VPC and on-premises - networks, or between VPC networks and internet hosts. A - reachability analysis is based on Google Cloud network - configurations. - - You can use the analysis results to verify these configurations - and to troubleshoot connectivity issues. - - 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 = 'networkmanagement.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: 'networkmanagement.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 = 'networkmanagement.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_connectivity_tests(self) -> Callable[ - [reachability.ListConnectivityTestsRequest], - reachability.ListConnectivityTestsResponse]: - r"""Return a callable for the list connectivity tests method over gRPC. - - Lists all Connectivity Tests owned by a project. - - Returns: - Callable[[~.ListConnectivityTestsRequest], - ~.ListConnectivityTestsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_connectivity_tests' not in self._stubs: - self._stubs['list_connectivity_tests'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/ListConnectivityTests', - request_serializer=reachability.ListConnectivityTestsRequest.serialize, - response_deserializer=reachability.ListConnectivityTestsResponse.deserialize, - ) - return self._stubs['list_connectivity_tests'] - - @property - def get_connectivity_test(self) -> Callable[ - [reachability.GetConnectivityTestRequest], - connectivity_test.ConnectivityTest]: - r"""Return a callable for the get connectivity test method over gRPC. - - Gets the details of a specific Connectivity Test. - - Returns: - Callable[[~.GetConnectivityTestRequest], - ~.ConnectivityTest]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_connectivity_test' not in self._stubs: - self._stubs['get_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/GetConnectivityTest', - request_serializer=reachability.GetConnectivityTestRequest.serialize, - response_deserializer=connectivity_test.ConnectivityTest.deserialize, - ) - return self._stubs['get_connectivity_test'] - - @property - def create_connectivity_test(self) -> Callable[ - [reachability.CreateConnectivityTestRequest], - operations_pb2.Operation]: - r"""Return a callable for the create connectivity test method over gRPC. - - Creates a new Connectivity Test. After you create a test, the - reachability analysis is performed as part of the long running - operation, which completes when the analysis completes. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, containing non-existent resources in the - network, or you don't have read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - AMBIGUOUS. For more information, see the Connectivity Test - documentation. - - Returns: - Callable[[~.CreateConnectivityTestRequest], - ~.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_connectivity_test' not in self._stubs: - self._stubs['create_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/CreateConnectivityTest', - request_serializer=reachability.CreateConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_connectivity_test'] - - @property - def update_connectivity_test(self) -> Callable[ - [reachability.UpdateConnectivityTestRequest], - operations_pb2.Operation]: - r"""Return a callable for the update connectivity test method over gRPC. - - Updates the configuration of an existing ``ConnectivityTest``. - After you update a test, the reachability analysis is performed - as part of the long running operation, which completes when the - analysis completes. The Reachability state in the test resource - is updated with the new result. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, they contain non-existent resources in the - network, or the user does not have read permissions to the - network configurations of listed projects), then the - reachability result returns a value of UNKNOWN. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for - more details. - - Returns: - Callable[[~.UpdateConnectivityTestRequest], - ~.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_connectivity_test' not in self._stubs: - self._stubs['update_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/UpdateConnectivityTest', - request_serializer=reachability.UpdateConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_connectivity_test'] - - @property - def rerun_connectivity_test(self) -> Callable[ - [reachability.RerunConnectivityTestRequest], - operations_pb2.Operation]: - r"""Return a callable for the rerun connectivity test method over gRPC. - - Rerun an existing ``ConnectivityTest``. After the user triggers - the rerun, the reachability analysis is performed as part of the - long running operation, which completes when the analysis - completes. - - Even though the test configuration remains the same, the - reachability result may change due to underlying network - configuration changes. - - If the endpoint specifications in ``ConnectivityTest`` become - invalid (for example, specified resources are deleted in the - network, or you lost read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - Returns: - Callable[[~.RerunConnectivityTestRequest], - ~.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 'rerun_connectivity_test' not in self._stubs: - self._stubs['rerun_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/RerunConnectivityTest', - request_serializer=reachability.RerunConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rerun_connectivity_test'] - - @property - def delete_connectivity_test(self) -> Callable[ - [reachability.DeleteConnectivityTestRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete connectivity test method over gRPC. - - Deletes a specific ``ConnectivityTest``. - - Returns: - Callable[[~.DeleteConnectivityTestRequest], - ~.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_connectivity_test' not in self._stubs: - self._stubs['delete_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/DeleteConnectivityTest', - request_serializer=reachability.DeleteConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_connectivity_test'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ReachabilityServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py deleted file mode 100644 index 15d349b57214..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,751 +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.location import locations_pb2 # type: ignore -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ReachabilityServiceGrpcTransport - - -class ReachabilityServiceGrpcAsyncIOTransport(ReachabilityServiceTransport): - """gRPC AsyncIO backend transport for ReachabilityService. - - The Reachability service in the Google Cloud Network - Management API provides services that analyze the reachability - within a single Google Virtual Private Cloud (VPC) network, - between peered VPC networks, between VPC and on-premises - networks, or between VPC networks and internet hosts. A - reachability analysis is based on Google Cloud network - configurations. - - You can use the analysis results to verify these configurations - and to troubleshoot connectivity issues. - - 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 = 'networkmanagement.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 = 'networkmanagement.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: 'networkmanagement.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_connectivity_tests(self) -> Callable[ - [reachability.ListConnectivityTestsRequest], - Awaitable[reachability.ListConnectivityTestsResponse]]: - r"""Return a callable for the list connectivity tests method over gRPC. - - Lists all Connectivity Tests owned by a project. - - Returns: - Callable[[~.ListConnectivityTestsRequest], - Awaitable[~.ListConnectivityTestsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_connectivity_tests' not in self._stubs: - self._stubs['list_connectivity_tests'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/ListConnectivityTests', - request_serializer=reachability.ListConnectivityTestsRequest.serialize, - response_deserializer=reachability.ListConnectivityTestsResponse.deserialize, - ) - return self._stubs['list_connectivity_tests'] - - @property - def get_connectivity_test(self) -> Callable[ - [reachability.GetConnectivityTestRequest], - Awaitable[connectivity_test.ConnectivityTest]]: - r"""Return a callable for the get connectivity test method over gRPC. - - Gets the details of a specific Connectivity Test. - - Returns: - Callable[[~.GetConnectivityTestRequest], - Awaitable[~.ConnectivityTest]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_connectivity_test' not in self._stubs: - self._stubs['get_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/GetConnectivityTest', - request_serializer=reachability.GetConnectivityTestRequest.serialize, - response_deserializer=connectivity_test.ConnectivityTest.deserialize, - ) - return self._stubs['get_connectivity_test'] - - @property - def create_connectivity_test(self) -> Callable[ - [reachability.CreateConnectivityTestRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create connectivity test method over gRPC. - - Creates a new Connectivity Test. After you create a test, the - reachability analysis is performed as part of the long running - operation, which completes when the analysis completes. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, containing non-existent resources in the - network, or you don't have read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - AMBIGUOUS. For more information, see the Connectivity Test - documentation. - - Returns: - Callable[[~.CreateConnectivityTestRequest], - 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_connectivity_test' not in self._stubs: - self._stubs['create_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/CreateConnectivityTest', - request_serializer=reachability.CreateConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_connectivity_test'] - - @property - def update_connectivity_test(self) -> Callable[ - [reachability.UpdateConnectivityTestRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update connectivity test method over gRPC. - - Updates the configuration of an existing ``ConnectivityTest``. - After you update a test, the reachability analysis is performed - as part of the long running operation, which completes when the - analysis completes. The Reachability state in the test resource - is updated with the new result. - - If the endpoint specifications in ``ConnectivityTest`` are - invalid (for example, they contain non-existent resources in the - network, or the user does not have read permissions to the - network configurations of listed projects), then the - reachability result returns a value of UNKNOWN. - - If the endpoint specifications in ``ConnectivityTest`` are - incomplete, the reachability result returns a value of - ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for - more details. - - Returns: - Callable[[~.UpdateConnectivityTestRequest], - 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_connectivity_test' not in self._stubs: - self._stubs['update_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/UpdateConnectivityTest', - request_serializer=reachability.UpdateConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_connectivity_test'] - - @property - def rerun_connectivity_test(self) -> Callable[ - [reachability.RerunConnectivityTestRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rerun connectivity test method over gRPC. - - Rerun an existing ``ConnectivityTest``. After the user triggers - the rerun, the reachability analysis is performed as part of the - long running operation, which completes when the analysis - completes. - - Even though the test configuration remains the same, the - reachability result may change due to underlying network - configuration changes. - - If the endpoint specifications in ``ConnectivityTest`` become - invalid (for example, specified resources are deleted in the - network, or you lost read permissions to the network - configurations of listed projects), then the reachability result - returns a value of ``UNKNOWN``. - - Returns: - Callable[[~.RerunConnectivityTestRequest], - 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 'rerun_connectivity_test' not in self._stubs: - self._stubs['rerun_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/RerunConnectivityTest', - request_serializer=reachability.RerunConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rerun_connectivity_test'] - - @property - def delete_connectivity_test(self) -> Callable[ - [reachability.DeleteConnectivityTestRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete connectivity test method over gRPC. - - Deletes a specific ``ConnectivityTest``. - - Returns: - Callable[[~.DeleteConnectivityTestRequest], - 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_connectivity_test' not in self._stubs: - self._stubs['delete_connectivity_test'] = self.grpc_channel.unary_unary( - '/google.cloud.networkmanagement.v1.ReachabilityService/DeleteConnectivityTest', - request_serializer=reachability.DeleteConnectivityTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_connectivity_test'] - - 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_connectivity_tests: self._wrap_method( - self.list_connectivity_tests, - default_timeout=None, - client_info=client_info, - ), - self.get_connectivity_test: self._wrap_method( - self.get_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.create_connectivity_test: self._wrap_method( - self.create_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.update_connectivity_test: self._wrap_method( - self.update_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.rerun_connectivity_test: self._wrap_method( - self.rerun_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.delete_connectivity_test: self._wrap_method( - self.delete_connectivity_test, - default_timeout=None, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self.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"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'ReachabilityServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py deleted file mode 100644 index aa84d74c181c..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest.py +++ /dev/null @@ -1,1714 +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.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseReachabilityServiceRestTransport -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 ReachabilityServiceRestInterceptor: - """Interceptor for ReachabilityService. - - 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 ReachabilityServiceRestTransport. - - .. code-block:: python - class MyCustomReachabilityServiceInterceptor(ReachabilityServiceRestInterceptor): - def pre_create_connectivity_test(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_connectivity_test(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_connectivity_test(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_connectivity_test(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_connectivity_test(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_connectivity_test(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_connectivity_tests(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_connectivity_tests(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_rerun_connectivity_test(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_rerun_connectivity_test(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_connectivity_test(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_connectivity_test(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ReachabilityServiceRestTransport(interceptor=MyCustomReachabilityServiceInterceptor()) - client = ReachabilityServiceClient(transport=transport) - - - """ - def pre_create_connectivity_test(self, request: reachability.CreateConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.CreateConnectivityTestRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_connectivity_test - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_create_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_connectivity_test - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_delete_connectivity_test(self, request: reachability.DeleteConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.DeleteConnectivityTestRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_connectivity_test - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_delete_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_connectivity_test - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_get_connectivity_test(self, request: reachability.GetConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.GetConnectivityTestRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_connectivity_test - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_get_connectivity_test(self, response: connectivity_test.ConnectivityTest) -> connectivity_test.ConnectivityTest: - """Post-rpc interceptor for get_connectivity_test - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_list_connectivity_tests(self, request: reachability.ListConnectivityTestsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.ListConnectivityTestsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_connectivity_tests - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_list_connectivity_tests(self, response: reachability.ListConnectivityTestsResponse) -> reachability.ListConnectivityTestsResponse: - """Post-rpc interceptor for list_connectivity_tests - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_rerun_connectivity_test(self, request: reachability.RerunConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.RerunConnectivityTestRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for rerun_connectivity_test - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_rerun_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for rerun_connectivity_test - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_update_connectivity_test(self, request: reachability.UpdateConnectivityTestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reachability.UpdateConnectivityTestRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_connectivity_test - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_update_connectivity_test(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_connectivity_test - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReachabilityService server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService 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 ReachabilityService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ReachabilityServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ReachabilityServiceRestInterceptor - - -class ReachabilityServiceRestTransport(_BaseReachabilityServiceRestTransport): - """REST backend synchronous transport for ReachabilityService. - - The Reachability service in the Google Cloud Network - Management API provides services that analyze the reachability - within a single Google Virtual Private Cloud (VPC) network, - between peered VPC networks, between VPC and on-premises - networks, or between VPC networks and internet hosts. A - reachability analysis is based on Google Cloud network - configurations. - - You can use the analysis results to verify these configurations - and to troubleshoot connectivity issues. - - 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 = 'networkmanagement.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[ReachabilityServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networkmanagement.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 ReachabilityServiceRestInterceptor() - 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/global/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/global/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/global/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/global}/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 _CreateConnectivityTest(_BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.CreateConnectivityTest") - - @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: reachability.CreateConnectivityTestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create connectivity test method over HTTP. - - Args: - request (~.reachability.CreateConnectivityTestRequest): - The request object. Request for the ``CreateConnectivityTest`` 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: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_http_options() - request, metadata = self._interceptor.pre_create_connectivity_test(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._CreateConnectivityTest._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_connectivity_test(resp) - return resp - - class _DeleteConnectivityTest(_BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.DeleteConnectivityTest") - - @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: reachability.DeleteConnectivityTestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete connectivity test method over HTTP. - - Args: - request (~.reachability.DeleteConnectivityTestRequest): - The request object. Request for the ``DeleteConnectivityTest`` 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: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_http_options() - request, metadata = self._interceptor.pre_delete_connectivity_test(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._DeleteConnectivityTest._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_connectivity_test(resp) - return resp - - class _GetConnectivityTest(_BaseReachabilityServiceRestTransport._BaseGetConnectivityTest, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.GetConnectivityTest") - - @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: reachability.GetConnectivityTestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> connectivity_test.ConnectivityTest: - r"""Call the get connectivity test method over HTTP. - - Args: - request (~.reachability.GetConnectivityTestRequest): - The request object. Request for the ``GetConnectivityTest`` 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: - ~.connectivity_test.ConnectivityTest: - A Connectivity Test for a network - reachability analysis. - - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_http_options() - request, metadata = self._interceptor.pre_get_connectivity_test(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._GetConnectivityTest._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 = connectivity_test.ConnectivityTest() - pb_resp = connectivity_test.ConnectivityTest.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_connectivity_test(resp) - return resp - - class _ListConnectivityTests(_BaseReachabilityServiceRestTransport._BaseListConnectivityTests, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.ListConnectivityTests") - - @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: reachability.ListConnectivityTestsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> reachability.ListConnectivityTestsResponse: - r"""Call the list connectivity tests method over HTTP. - - Args: - request (~.reachability.ListConnectivityTestsRequest): - The request object. Request for the ``ListConnectivityTests`` 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: - ~.reachability.ListConnectivityTestsResponse: - Response for the ``ListConnectivityTests`` method. - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_http_options() - request, metadata = self._interceptor.pre_list_connectivity_tests(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._ListConnectivityTests._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 = reachability.ListConnectivityTestsResponse() - pb_resp = reachability.ListConnectivityTestsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_connectivity_tests(resp) - return resp - - class _RerunConnectivityTest(_BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.RerunConnectivityTest") - - @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: reachability.RerunConnectivityTestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the rerun connectivity test method over HTTP. - - Args: - request (~.reachability.RerunConnectivityTestRequest): - The request object. Request for the ``RerunConnectivityTest`` 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: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_http_options() - request, metadata = self._interceptor.pre_rerun_connectivity_test(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._RerunConnectivityTest._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_rerun_connectivity_test(resp) - return resp - - class _UpdateConnectivityTest(_BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.UpdateConnectivityTest") - - @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: reachability.UpdateConnectivityTestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update connectivity test method over HTTP. - - Args: - request (~.reachability.UpdateConnectivityTestRequest): - The request object. Request for the ``UpdateConnectivityTest`` 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: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_http_options() - request, metadata = self._interceptor.pre_update_connectivity_test(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._UpdateConnectivityTest._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_connectivity_test(resp) - return resp - - @property - def create_connectivity_test(self) -> Callable[ - [reachability.CreateConnectivityTestRequest], - 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._CreateConnectivityTest(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_connectivity_test(self) -> Callable[ - [reachability.DeleteConnectivityTestRequest], - 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._DeleteConnectivityTest(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_connectivity_test(self) -> Callable[ - [reachability.GetConnectivityTestRequest], - connectivity_test.ConnectivityTest]: - # 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._GetConnectivityTest(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_connectivity_tests(self) -> Callable[ - [reachability.ListConnectivityTestsRequest], - reachability.ListConnectivityTestsResponse]: - # 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._ListConnectivityTests(self._session, self._host, self._interceptor) # type: ignore - - @property - def rerun_connectivity_test(self) -> Callable[ - [reachability.RerunConnectivityTestRequest], - 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._RerunConnectivityTest(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_connectivity_test(self) -> Callable[ - [reachability.UpdateConnectivityTestRequest], - 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._UpdateConnectivityTest(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(_BaseReachabilityServiceRestTransport._BaseGetLocation, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseListLocations, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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 get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseReachabilityServiceRestTransport._BaseGetIamPolicy, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseReachabilityServiceRestTransport._BaseSetIamPolicy, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseReachabilityServiceRestTransport._BaseTestIamPermissions, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseReachabilityServiceRestTransport._BaseCancelOperation, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_http_options() - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseDeleteOperation, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_http_options() - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseGetOperation, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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(_BaseReachabilityServiceRestTransport._BaseListOperations, ReachabilityServiceRestStub): - def __hash__(self): - return hash("ReachabilityServiceRestTransport.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 = _BaseReachabilityServiceRestTransport._BaseListOperations._get_http_options() - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseReachabilityServiceRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseReachabilityServiceRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - # Send the request - response = ReachabilityServiceRestTransport._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__=( - 'ReachabilityServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py deleted file mode 100644 index 7dd2991844be..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/services/reachability_service/transports/rest_base.py +++ /dev/null @@ -1,588 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseReachabilityServiceRestTransport(ReachabilityServiceTransport): - """Base REST backend transport for ReachabilityService. - - 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 = 'networkmanagement.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: 'networkmanagement.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 _BaseCreateConnectivityTest: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "testId" : "", } - - @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/global}/connectivityTests', - 'body': 'resource', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.CreateConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseCreateConnectivityTest._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteConnectivityTest: - 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/global/connectivityTests/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.DeleteConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseDeleteConnectivityTest._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetConnectivityTest: - 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/global/connectivityTests/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.GetConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseGetConnectivityTest._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListConnectivityTests: - 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/global}/connectivityTests', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.ListConnectivityTestsRequest.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(_BaseReachabilityServiceRestTransport._BaseListConnectivityTests._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseRerunConnectivityTest: - 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/global/connectivityTests/*}:rerun', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.RerunConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseRerunConnectivityTest._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateConnectivityTest: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{resource.name=projects/*/locations/global/connectivityTests/*}', - 'body': 'resource', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reachability.UpdateConnectivityTestRequest.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(_BaseReachabilityServiceRestTransport._BaseUpdateConnectivityTest._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLocation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListLocations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:getIamPolicy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/global/connectivityTests/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseCancelOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/global/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/global/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/global/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/global}/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__=( - '_BaseReachabilityServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/__init__.py deleted file mode 100644 index ce14d0c9af68..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_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 .connectivity_test import ( - ConnectivityTest, - Endpoint, - LatencyDistribution, - LatencyPercentile, - ProbingDetails, - ReachabilityDetails, -) -from .reachability import ( - CreateConnectivityTestRequest, - DeleteConnectivityTestRequest, - GetConnectivityTestRequest, - ListConnectivityTestsRequest, - ListConnectivityTestsResponse, - OperationMetadata, - RerunConnectivityTestRequest, - UpdateConnectivityTestRequest, -) -from .trace import ( - AbortInfo, - AppEngineVersionInfo, - CloudFunctionInfo, - CloudRunRevisionInfo, - CloudSQLInstanceInfo, - DeliverInfo, - DropInfo, - EndpointInfo, - FirewallInfo, - ForwardInfo, - ForwardingRuleInfo, - GKEMasterInfo, - GoogleServiceInfo, - InstanceInfo, - LoadBalancerBackend, - LoadBalancerBackendInfo, - LoadBalancerInfo, - NatInfo, - NetworkInfo, - ProxyConnectionInfo, - RedisClusterInfo, - RedisInstanceInfo, - RouteInfo, - ServerlessNegInfo, - Step, - StorageBucketInfo, - Trace, - VpcConnectorInfo, - VpnGatewayInfo, - VpnTunnelInfo, - LoadBalancerType, -) - -__all__ = ( - 'ConnectivityTest', - 'Endpoint', - 'LatencyDistribution', - 'LatencyPercentile', - 'ProbingDetails', - 'ReachabilityDetails', - 'CreateConnectivityTestRequest', - 'DeleteConnectivityTestRequest', - 'GetConnectivityTestRequest', - 'ListConnectivityTestsRequest', - 'ListConnectivityTestsResponse', - 'OperationMetadata', - 'RerunConnectivityTestRequest', - 'UpdateConnectivityTestRequest', - 'AbortInfo', - 'AppEngineVersionInfo', - 'CloudFunctionInfo', - 'CloudRunRevisionInfo', - 'CloudSQLInstanceInfo', - 'DeliverInfo', - 'DropInfo', - 'EndpointInfo', - 'FirewallInfo', - 'ForwardInfo', - 'ForwardingRuleInfo', - 'GKEMasterInfo', - 'GoogleServiceInfo', - 'InstanceInfo', - 'LoadBalancerBackend', - 'LoadBalancerBackendInfo', - 'LoadBalancerInfo', - 'NatInfo', - 'NetworkInfo', - 'ProxyConnectionInfo', - 'RedisClusterInfo', - 'RedisInstanceInfo', - 'RouteInfo', - 'ServerlessNegInfo', - 'Step', - 'StorageBucketInfo', - 'Trace', - 'VpcConnectorInfo', - 'VpnGatewayInfo', - 'VpnTunnelInfo', - 'LoadBalancerType', -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py deleted file mode 100644 index 9e8dc38fbf27..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/connectivity_test.py +++ /dev/null @@ -1,753 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.network_management_v1.types import trace -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networkmanagement.v1', - manifest={ - 'ConnectivityTest', - 'Endpoint', - 'ReachabilityDetails', - 'LatencyPercentile', - 'LatencyDistribution', - 'ProbingDetails', - }, -) - - -class ConnectivityTest(proto.Message): - r"""A Connectivity Test for a network reachability analysis. - - Attributes: - name (str): - Identifier. Unique name of the resource using the form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - description (str): - The user-supplied description of the - Connectivity Test. Maximum of 512 characters. - source (google.cloud.network_management_v1.types.Endpoint): - Required. Source specification of the - Connectivity Test. - You can use a combination of source IP address, - virtual machine (VM) instance, or Compute Engine - network to uniquely identify the source - location. - - Examples: - - If the source IP address is an internal IP - address within a Google Cloud Virtual Private - Cloud (VPC) network, then you must also specify - the VPC network. Otherwise, specify the VM - instance, which already contains its internal IP - address and VPC network information. - - If the source of the test is within an - on-premises network, then you must provide the - destination VPC network. - - If the source endpoint is a Compute Engine VM - instance with multiple network interfaces, the - instance itself is not sufficient to identify - the endpoint. So, you must also specify the - source IP address or VPC network. - - A reachability analysis proceeds even if the - source location is ambiguous. However, the test - result may include endpoints that you don't - intend to test. - destination (google.cloud.network_management_v1.types.Endpoint): - Required. Destination specification of the - Connectivity Test. - You can use a combination of destination IP - address, Compute Engine VM instance, or VPC - network to uniquely identify the destination - location. - - Even if the destination IP address is not - unique, the source IP location is unique. - Usually, the analysis can infer the destination - endpoint from route information. - - If the destination you specify is a VM instance - and the instance has multiple network - interfaces, then you must also specify either a - destination IP address or VPC network to - identify the destination interface. - - A reachability analysis proceeds even if the - destination location is ambiguous. However, the - result can include endpoints that you don't - intend to test. - protocol (str): - IP Protocol of the test. When not provided, - "TCP" is assumed. - related_projects (MutableSequence[str]): - Other projects that may be relevant for - reachability analysis. This is applicable to - scenarios where a test can cross project - boundaries. - display_name (str): - Output only. The display name of a - Connectivity Test. - labels (MutableMapping[str, str]): - Resource labels to represent user-provided - metadata. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the test was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the test's - configuration was updated. - reachability_details (google.cloud.network_management_v1.types.ReachabilityDetails): - Output only. The reachability details of this - test from the latest run. The details are - updated when creating a new test, updating an - existing test, or triggering a one-time rerun of - an existing test. - probing_details (google.cloud.network_management_v1.types.ProbingDetails): - Output only. The probing details of this test - from the latest run, present for applicable - tests only. The details are updated when - creating a new test, updating an existing test, - or triggering a one-time rerun of an existing - test. - round_trip (bool): - Whether run analysis for the return path from - destination to source. Default value is false. - return_reachability_details (google.cloud.network_management_v1.types.ReachabilityDetails): - Output only. The reachability details of this - test from the latest run for the return path. - The details are updated when creating a new - test, updating an existing test, or triggering a - one-time rerun of an existing test. - bypass_firewall_checks (bool): - Whether the test should skip firewall - checking. If not provided, we assume false. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - source: 'Endpoint' = proto.Field( - proto.MESSAGE, - number=3, - message='Endpoint', - ) - destination: 'Endpoint' = proto.Field( - proto.MESSAGE, - number=4, - message='Endpoint', - ) - protocol: str = proto.Field( - proto.STRING, - number=5, - ) - related_projects: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - display_name: str = proto.Field( - proto.STRING, - number=7, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - reachability_details: 'ReachabilityDetails' = proto.Field( - proto.MESSAGE, - number=12, - message='ReachabilityDetails', - ) - probing_details: 'ProbingDetails' = proto.Field( - proto.MESSAGE, - number=14, - message='ProbingDetails', - ) - round_trip: bool = proto.Field( - proto.BOOL, - number=15, - ) - return_reachability_details: 'ReachabilityDetails' = proto.Field( - proto.MESSAGE, - number=16, - message='ReachabilityDetails', - ) - bypass_firewall_checks: bool = proto.Field( - proto.BOOL, - number=17, - ) - - -class Endpoint(proto.Message): - r"""Source or destination of the Connectivity Test. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - ip_address (str): - The IP address of the endpoint, which can be - an external or internal IP. - port (int): - The IP protocol port of the endpoint. - Only applicable when protocol is TCP or UDP. - instance (str): - A Compute Engine instance URI. - forwarding_rule (str): - A forwarding rule and its corresponding IP - address represent the frontend configuration of - a Google Cloud load balancer. Forwarding rules - are also used for protocol forwarding, Private - Service Connect and other network services to - provide forwarding information in the control - plane. Format: - - projects/{project}/global/forwardingRules/{id} - or - projects/{project}/regions/{region}/forwardingRules/{id} - forwarding_rule_target (google.cloud.network_management_v1.types.Endpoint.ForwardingRuleTarget): - Output only. Specifies the type of the target - of the forwarding rule. - - This field is a member of `oneof`_ ``_forwarding_rule_target``. - load_balancer_id (str): - Output only. ID of the load balancer the - forwarding rule points to. Empty for forwarding - rules not related to load balancers. - - This field is a member of `oneof`_ ``_load_balancer_id``. - load_balancer_type (google.cloud.network_management_v1.types.LoadBalancerType): - Output only. Type of the load balancer the - forwarding rule points to. - - This field is a member of `oneof`_ ``_load_balancer_type``. - gke_master_cluster (str): - A cluster URI for `Google Kubernetes Engine cluster control - plane `__. - fqdn (str): - DNS endpoint of `Google Kubernetes Engine cluster control - plane `__. - Requires gke_master_cluster to be set, can't be used - simultaneoulsly with ip_address or network. Applicable only - to destination endpoint. - cloud_sql_instance (str): - A `Cloud SQL `__ instance URI. - redis_instance (str): - A `Redis - Instance `__ - URI. - redis_cluster (str): - A `Redis - Cluster `__ - URI. - cloud_function (google.cloud.network_management_v1.types.Endpoint.CloudFunctionEndpoint): - A `Cloud Function `__. - app_engine_version (google.cloud.network_management_v1.types.Endpoint.AppEngineVersionEndpoint): - An `App Engine `__ - `service - version `__. - cloud_run_revision (google.cloud.network_management_v1.types.Endpoint.CloudRunRevisionEndpoint): - A `Cloud Run `__ - `revision `__ - network (str): - A Compute Engine network URI. - network_type (google.cloud.network_management_v1.types.Endpoint.NetworkType): - Type of the network where the endpoint is - located. Applicable only to source endpoint, as - destination network type can be inferred from - the source. - project_id (str): - Project ID where the endpoint is located. - The Project ID can be derived from the URI if - you provide a VM instance or network URI. - The following are two cases where you must - provide the project ID: - - 1. Only the IP address is specified, and the IP - address is within a Google Cloud project. - 2. When you are using Shared VPC and the IP - address that you provide is from the service - project. In this case, the network that the - IP address resides in is defined in the host - project. - """ - class NetworkType(proto.Enum): - r"""The type definition of an endpoint's network. Use one of the - following choices: - - Values: - NETWORK_TYPE_UNSPECIFIED (0): - Default type if unspecified. - GCP_NETWORK (1): - A network hosted within Google Cloud. - To receive more detailed output, specify the URI - for the source or destination network. - NON_GCP_NETWORK (2): - A network hosted outside of Google Cloud. - This can be an on-premises network, or a network - hosted by another cloud provider. - """ - NETWORK_TYPE_UNSPECIFIED = 0 - GCP_NETWORK = 1 - NON_GCP_NETWORK = 2 - - class ForwardingRuleTarget(proto.Enum): - r"""Type of the target of a forwarding rule. - - Values: - FORWARDING_RULE_TARGET_UNSPECIFIED (0): - Forwarding rule target is unknown. - INSTANCE (1): - Compute Engine instance for protocol - forwarding. - LOAD_BALANCER (2): - Load Balancer. The specific type can be found from - [load_balancer_type] - [google.cloud.networkmanagement.v1.Endpoint.load_balancer_type]. - VPN_GATEWAY (3): - Classic Cloud VPN Gateway. - PSC (4): - Forwarding Rule is a Private Service Connect - endpoint. - """ - FORWARDING_RULE_TARGET_UNSPECIFIED = 0 - INSTANCE = 1 - LOAD_BALANCER = 2 - VPN_GATEWAY = 3 - PSC = 4 - - class CloudFunctionEndpoint(proto.Message): - r"""Wrapper for Cloud Function attributes. - - Attributes: - uri (str): - A `Cloud Function `__ - name. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - class AppEngineVersionEndpoint(proto.Message): - r"""Wrapper for the App Engine service version attributes. - - Attributes: - uri (str): - An `App Engine `__ - `service - version `__ - name. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - class CloudRunRevisionEndpoint(proto.Message): - r"""Wrapper for Cloud Run revision attributes. - - Attributes: - uri (str): - A `Cloud Run `__ - `revision `__ - URI. The format is: - projects/{project}/locations/{location}/revisions/{revision} - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - ip_address: str = proto.Field( - proto.STRING, - number=1, - ) - port: int = proto.Field( - proto.INT32, - number=2, - ) - instance: str = proto.Field( - proto.STRING, - number=3, - ) - forwarding_rule: str = proto.Field( - proto.STRING, - number=13, - ) - forwarding_rule_target: ForwardingRuleTarget = proto.Field( - proto.ENUM, - number=14, - optional=True, - enum=ForwardingRuleTarget, - ) - load_balancer_id: str = proto.Field( - proto.STRING, - number=15, - optional=True, - ) - load_balancer_type: trace.LoadBalancerType = proto.Field( - proto.ENUM, - number=16, - optional=True, - enum=trace.LoadBalancerType, - ) - gke_master_cluster: str = proto.Field( - proto.STRING, - number=7, - ) - fqdn: str = proto.Field( - proto.STRING, - number=19, - ) - cloud_sql_instance: str = proto.Field( - proto.STRING, - number=8, - ) - redis_instance: str = proto.Field( - proto.STRING, - number=17, - ) - redis_cluster: str = proto.Field( - proto.STRING, - number=18, - ) - cloud_function: CloudFunctionEndpoint = proto.Field( - proto.MESSAGE, - number=10, - message=CloudFunctionEndpoint, - ) - app_engine_version: AppEngineVersionEndpoint = proto.Field( - proto.MESSAGE, - number=11, - message=AppEngineVersionEndpoint, - ) - cloud_run_revision: CloudRunRevisionEndpoint = proto.Field( - proto.MESSAGE, - number=12, - message=CloudRunRevisionEndpoint, - ) - network: str = proto.Field( - proto.STRING, - number=4, - ) - network_type: NetworkType = proto.Field( - proto.ENUM, - number=5, - enum=NetworkType, - ) - project_id: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ReachabilityDetails(proto.Message): - r"""Results of the configuration analysis from the last run of - the test. - - Attributes: - result (google.cloud.network_management_v1.types.ReachabilityDetails.Result): - The overall result of the test's - configuration analysis. - verify_time (google.protobuf.timestamp_pb2.Timestamp): - The time of the configuration analysis. - error (google.rpc.status_pb2.Status): - The details of a failure or a cancellation of - reachability analysis. - traces (MutableSequence[google.cloud.network_management_v1.types.Trace]): - Result may contain a list of traces if a test - has multiple possible paths in the network, such - as when destination endpoint is a load balancer - with multiple backends. - """ - class Result(proto.Enum): - r"""The overall result of the test's configuration analysis. - - Values: - RESULT_UNSPECIFIED (0): - No result was specified. - REACHABLE (1): - Possible scenarios are: - - - The configuration analysis determined that a packet - originating from the source is expected to reach the - destination. - - The analysis didn't complete because the user lacks - permission for some of the resources in the trace. - However, at the time the user's permission became - insufficient, the trace had been successful so far. - UNREACHABLE (2): - A packet originating from the source is - expected to be dropped before reaching the - destination. - AMBIGUOUS (4): - The source and destination endpoints do not - uniquely identify the test location in the - network, and the reachability result contains - multiple traces. For some traces, a packet could - be delivered, and for others, it would not be. - This result is also assigned to configuration - analysis of return path if on its own it should - be REACHABLE, but configuration analysis of - forward path is AMBIGUOUS. - UNDETERMINED (5): - The configuration analysis did not complete. Possible - reasons are: - - - A permissions error occurred--for example, the user might - not have read permission for all of the resources named - in the test. - - An internal error occurred. - - The analyzer received an invalid or unsupported argument - or was unable to identify a known endpoint. - """ - RESULT_UNSPECIFIED = 0 - REACHABLE = 1 - UNREACHABLE = 2 - AMBIGUOUS = 4 - UNDETERMINED = 5 - - result: Result = proto.Field( - proto.ENUM, - number=1, - enum=Result, - ) - verify_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - traces: MutableSequence[trace.Trace] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=trace.Trace, - ) - - -class LatencyPercentile(proto.Message): - r"""Latency percentile rank and value. - - Attributes: - percent (int): - Percentage of samples this data point applies - to. - latency_micros (int): - percent-th percentile of latency observed, in - microseconds. Fraction of percent/100 of samples - have latency lower or equal to the value of this - field. - """ - - percent: int = proto.Field( - proto.INT32, - number=1, - ) - latency_micros: int = proto.Field( - proto.INT64, - number=2, - ) - - -class LatencyDistribution(proto.Message): - r"""Describes measured latency distribution. - - Attributes: - latency_percentiles (MutableSequence[google.cloud.network_management_v1.types.LatencyPercentile]): - Representative latency percentiles. - """ - - latency_percentiles: MutableSequence['LatencyPercentile'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LatencyPercentile', - ) - - -class ProbingDetails(proto.Message): - r"""Results of active probing from the last run of the test. - - Attributes: - result (google.cloud.network_management_v1.types.ProbingDetails.ProbingResult): - The overall result of active probing. - verify_time (google.protobuf.timestamp_pb2.Timestamp): - The time that reachability was assessed - through active probing. - error (google.rpc.status_pb2.Status): - Details about an internal failure or the - cancellation of active probing. - abort_cause (google.cloud.network_management_v1.types.ProbingDetails.ProbingAbortCause): - The reason probing was aborted. - sent_probe_count (int): - Number of probes sent. - successful_probe_count (int): - Number of probes that reached the - destination. - endpoint_info (google.cloud.network_management_v1.types.EndpointInfo): - The source and destination endpoints derived - from the test input and used for active probing. - probing_latency (google.cloud.network_management_v1.types.LatencyDistribution): - Latency as measured by active probing in one - direction: from the source to the destination - endpoint. - destination_egress_location (google.cloud.network_management_v1.types.ProbingDetails.EdgeLocation): - The EdgeLocation from which a packet destined - for/originating from the internet will egress/ingress the - Google network. This will only be populated for a - connectivity test which has an internet destination/source - address. The absence of this field *must not* be used as an - indication that the destination/source is part of the Google - network. - """ - class ProbingResult(proto.Enum): - r"""Overall probing result of the test. - - Values: - PROBING_RESULT_UNSPECIFIED (0): - No result was specified. - REACHABLE (1): - At least 95% of packets reached the - destination. - UNREACHABLE (2): - No packets reached the destination. - REACHABILITY_INCONSISTENT (3): - Less than 95% of packets reached the - destination. - UNDETERMINED (4): - Reachability could not be determined. Possible reasons are: - - - The user lacks permission to access some of the network - resources required to run the test. - - No valid source endpoint could be derived from the - request. - - An internal error occurred. - """ - PROBING_RESULT_UNSPECIFIED = 0 - REACHABLE = 1 - UNREACHABLE = 2 - REACHABILITY_INCONSISTENT = 3 - UNDETERMINED = 4 - - class ProbingAbortCause(proto.Enum): - r"""Abort cause types. - - Values: - PROBING_ABORT_CAUSE_UNSPECIFIED (0): - No reason was specified. - PERMISSION_DENIED (1): - The user lacks permission to access some of - the network resources required to run the test. - NO_SOURCE_LOCATION (2): - No valid source endpoint could be derived - from the request. - """ - PROBING_ABORT_CAUSE_UNSPECIFIED = 0 - PERMISSION_DENIED = 1 - NO_SOURCE_LOCATION = 2 - - class EdgeLocation(proto.Message): - r"""Representation of a network edge location as per - https://cloud.google.com/vpc/docs/edge-locations. - - Attributes: - metropolitan_area (str): - Name of the metropolitan area. - """ - - metropolitan_area: str = proto.Field( - proto.STRING, - number=1, - ) - - result: ProbingResult = proto.Field( - proto.ENUM, - number=1, - enum=ProbingResult, - ) - verify_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - abort_cause: ProbingAbortCause = proto.Field( - proto.ENUM, - number=4, - enum=ProbingAbortCause, - ) - sent_probe_count: int = proto.Field( - proto.INT32, - number=5, - ) - successful_probe_count: int = proto.Field( - proto.INT32, - number=6, - ) - endpoint_info: trace.EndpointInfo = proto.Field( - proto.MESSAGE, - number=7, - message=trace.EndpointInfo, - ) - probing_latency: 'LatencyDistribution' = proto.Field( - proto.MESSAGE, - number=8, - message='LatencyDistribution', - ) - destination_egress_location: EdgeLocation = proto.Field( - proto.MESSAGE, - number=9, - message=EdgeLocation, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py deleted file mode 100644 index ed3cdf469712..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/reachability.py +++ /dev/null @@ -1,293 +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.network_management_v1.types import connectivity_test -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networkmanagement.v1', - manifest={ - 'ListConnectivityTestsRequest', - 'ListConnectivityTestsResponse', - 'GetConnectivityTestRequest', - 'CreateConnectivityTestRequest', - 'UpdateConnectivityTestRequest', - 'DeleteConnectivityTestRequest', - 'RerunConnectivityTestRequest', - 'OperationMetadata', - }, -) - - -class ListConnectivityTestsRequest(proto.Message): - r"""Request for the ``ListConnectivityTests`` method. - - Attributes: - parent (str): - Required. The parent resource of the Connectivity Tests: - ``projects/{project_id}/locations/global`` - page_size (int): - Number of ``ConnectivityTests`` to return. - page_token (str): - Page token from an earlier query, as returned in - ``next_page_token``. - filter (str): - Lists the ``ConnectivityTests`` that match the filter - expression. A filter expression filters the resources listed - in the response. The expression must be of the form - `` `` where operators: ``<``, - ``>``, ``<=``, ``>=``, ``!=``, ``=``, ``:`` are supported - (colon ``:`` represents a HAS operator which is roughly - synonymous with equality). can refer to a proto or JSON - field, or a synthetic field. Field names can be camelCase or - snake_case. - - Examples: - - - Filter by name: name = - "projects/proj-1/locations/global/connectivityTests/test-1 - - - Filter by labels: - - - Resources that have a key called ``foo`` labels.foo:\* - - Resources that have a key called ``foo`` whose value - is ``bar`` labels.foo = bar - order_by (str): - Field to use to sort the list. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListConnectivityTestsResponse(proto.Message): - r"""Response for the ``ListConnectivityTests`` method. - - Attributes: - resources (MutableSequence[google.cloud.network_management_v1.types.ConnectivityTest]): - List of Connectivity Tests. - next_page_token (str): - Page token to fetch the next set of - Connectivity Tests. - unreachable (MutableSequence[str]): - Locations that could not be reached (when querying all - locations with ``-``). - """ - - @property - def raw_page(self): - return self - - resources: MutableSequence[connectivity_test.ConnectivityTest] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=connectivity_test.ConnectivityTest, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetConnectivityTestRequest(proto.Message): - r"""Request for the ``GetConnectivityTest`` method. - - Attributes: - name (str): - Required. ``ConnectivityTest`` resource name using the form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateConnectivityTestRequest(proto.Message): - r"""Request for the ``CreateConnectivityTest`` method. - - Attributes: - parent (str): - Required. The parent resource of the Connectivity Test to - create: ``projects/{project_id}/locations/global`` - test_id (str): - Required. The logical name of the Connectivity Test in your - project with the following restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-40 characters. - - Must end with a number or a letter. - - Must be unique within the customer project - resource (google.cloud.network_management_v1.types.ConnectivityTest): - Required. A ``ConnectivityTest`` resource - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - test_id: str = proto.Field( - proto.STRING, - number=2, - ) - resource: connectivity_test.ConnectivityTest = proto.Field( - proto.MESSAGE, - number=3, - message=connectivity_test.ConnectivityTest, - ) - - -class UpdateConnectivityTestRequest(proto.Message): - r"""Request for the ``UpdateConnectivityTest`` method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask of fields to update. At least - one path must be supplied in this field. - resource (google.cloud.network_management_v1.types.ConnectivityTest): - Required. Only fields specified in update_mask are updated. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - resource: connectivity_test.ConnectivityTest = proto.Field( - proto.MESSAGE, - number=2, - message=connectivity_test.ConnectivityTest, - ) - - -class DeleteConnectivityTestRequest(proto.Message): - r"""Request for the ``DeleteConnectivityTest`` method. - - Attributes: - name (str): - Required. Connectivity Test resource name using the form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class RerunConnectivityTestRequest(proto.Message): - r"""Request for the ``RerunConnectivityTest`` method. - - Attributes: - name (str): - Required. Connectivity Test resource name using the form: - ``projects/{project_id}/locations/global/connectivityTests/{test_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class OperationMetadata(proto.Message): - r"""Metadata describing an [Operation][google.longrunning.Operation] - - 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): - Target of the operation - for example - projects/project-1/locations/global/connectivityTests/test-1 - verb (str): - Name of the verb executed by the operation. - status_detail (str): - Human-readable status of the operation, if - any. - cancel_requested (bool): - Specifies if cancellation was requested for - the operation. - api_version (str): - API version. - """ - - 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_detail: str = proto.Field( - proto.STRING, - number=5, - ) - cancel_requested: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py b/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py deleted file mode 100644 index 78741f3894e1..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/google/cloud/network_management_v1/types/trace.py +++ /dev/null @@ -1,3164 +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 - - -__protobuf__ = proto.module( - package='google.cloud.networkmanagement.v1', - manifest={ - 'LoadBalancerType', - 'Trace', - 'Step', - 'InstanceInfo', - 'NetworkInfo', - 'FirewallInfo', - 'RouteInfo', - 'GoogleServiceInfo', - 'ForwardingRuleInfo', - 'LoadBalancerInfo', - 'LoadBalancerBackend', - 'VpnGatewayInfo', - 'VpnTunnelInfo', - 'EndpointInfo', - 'DeliverInfo', - 'ForwardInfo', - 'AbortInfo', - 'DropInfo', - 'GKEMasterInfo', - 'CloudSQLInstanceInfo', - 'RedisInstanceInfo', - 'RedisClusterInfo', - 'CloudFunctionInfo', - 'CloudRunRevisionInfo', - 'AppEngineVersionInfo', - 'VpcConnectorInfo', - 'NatInfo', - 'ProxyConnectionInfo', - 'LoadBalancerBackendInfo', - 'StorageBucketInfo', - 'ServerlessNegInfo', - }, -) - - -class LoadBalancerType(proto.Enum): - r"""Type of a load balancer. For more information, see `Summary of - Google Cloud load - balancers `__. - - Values: - LOAD_BALANCER_TYPE_UNSPECIFIED (0): - Forwarding rule points to a different target - than a load balancer or a load balancer type is - unknown. - HTTPS_ADVANCED_LOAD_BALANCER (1): - Global external HTTP(S) load balancer. - HTTPS_LOAD_BALANCER (2): - Global external HTTP(S) load balancer - (classic) - REGIONAL_HTTPS_LOAD_BALANCER (3): - Regional external HTTP(S) load balancer. - INTERNAL_HTTPS_LOAD_BALANCER (4): - Internal HTTP(S) load balancer. - SSL_PROXY_LOAD_BALANCER (5): - External SSL proxy load balancer. - TCP_PROXY_LOAD_BALANCER (6): - External TCP proxy load balancer. - INTERNAL_TCP_PROXY_LOAD_BALANCER (7): - Internal regional TCP proxy load balancer. - NETWORK_LOAD_BALANCER (8): - External TCP/UDP Network load balancer. - LEGACY_NETWORK_LOAD_BALANCER (9): - Target-pool based external TCP/UDP Network - load balancer. - TCP_UDP_INTERNAL_LOAD_BALANCER (10): - Internal TCP/UDP load balancer. - """ - LOAD_BALANCER_TYPE_UNSPECIFIED = 0 - HTTPS_ADVANCED_LOAD_BALANCER = 1 - HTTPS_LOAD_BALANCER = 2 - REGIONAL_HTTPS_LOAD_BALANCER = 3 - INTERNAL_HTTPS_LOAD_BALANCER = 4 - SSL_PROXY_LOAD_BALANCER = 5 - TCP_PROXY_LOAD_BALANCER = 6 - INTERNAL_TCP_PROXY_LOAD_BALANCER = 7 - NETWORK_LOAD_BALANCER = 8 - LEGACY_NETWORK_LOAD_BALANCER = 9 - TCP_UDP_INTERNAL_LOAD_BALANCER = 10 - - -class Trace(proto.Message): - r"""Trace represents one simulated packet forwarding path. - - - Each trace contains multiple ordered steps. - - Each step is in a particular state with associated configuration. - - State is categorized as final or non-final states. - - Each final state has a reason associated. - - Each trace must end with a final state (the last step). - - :: - - |---------------------Trace----------------------| - Step1(State) Step2(State) --- StepN(State(final)) - - Attributes: - endpoint_info (google.cloud.network_management_v1.types.EndpointInfo): - Derived from the source and destination endpoints definition - specified by user request, and validated by the data plane - model. If there are multiple traces starting from different - source locations, then the endpoint_info may be different - between traces. - steps (MutableSequence[google.cloud.network_management_v1.types.Step]): - A trace of a test contains multiple steps - from the initial state to the final state - (delivered, dropped, forwarded, or aborted). - - The steps are ordered by the processing sequence - within the simulated network state machine. It - is critical to preserve the order of the steps - and avoid reordering or sorting them. - forward_trace_id (int): - ID of trace. For forward traces, this ID is - unique for each trace. For return traces, it - matches ID of associated forward trace. A single - forward trace can be associated with none, one - or more than one return trace. - """ - - endpoint_info: 'EndpointInfo' = proto.Field( - proto.MESSAGE, - number=1, - message='EndpointInfo', - ) - steps: MutableSequence['Step'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Step', - ) - forward_trace_id: int = proto.Field( - proto.INT32, - number=4, - ) - - -class Step(proto.Message): - r"""A simulated forwarding path is composed of multiple steps. - Each step has a well-defined state and an associated - configuration. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - description (str): - A description of the step. Usually this is a - summary of the state. - state (google.cloud.network_management_v1.types.Step.State): - Each step is in one of the pre-defined - states. - causes_drop (bool): - This is a step that leads to the final state - Drop. - project_id (str): - Project ID that contains the configuration - this step is validating. - instance (google.cloud.network_management_v1.types.InstanceInfo): - Display information of a Compute Engine - instance. - - This field is a member of `oneof`_ ``step_info``. - firewall (google.cloud.network_management_v1.types.FirewallInfo): - Display information of a Compute Engine - firewall rule. - - This field is a member of `oneof`_ ``step_info``. - route (google.cloud.network_management_v1.types.RouteInfo): - Display information of a Compute Engine - route. - - This field is a member of `oneof`_ ``step_info``. - endpoint (google.cloud.network_management_v1.types.EndpointInfo): - Display information of the source and - destination under analysis. The endpoint - information in an intermediate state may differ - with the initial input, as it might be modified - by state like NAT, or Connection Proxy. - - This field is a member of `oneof`_ ``step_info``. - google_service (google.cloud.network_management_v1.types.GoogleServiceInfo): - Display information of a Google service - - This field is a member of `oneof`_ ``step_info``. - forwarding_rule (google.cloud.network_management_v1.types.ForwardingRuleInfo): - Display information of a Compute Engine - forwarding rule. - - This field is a member of `oneof`_ ``step_info``. - vpn_gateway (google.cloud.network_management_v1.types.VpnGatewayInfo): - Display information of a Compute Engine VPN - gateway. - - This field is a member of `oneof`_ ``step_info``. - vpn_tunnel (google.cloud.network_management_v1.types.VpnTunnelInfo): - Display information of a Compute Engine VPN - tunnel. - - This field is a member of `oneof`_ ``step_info``. - vpc_connector (google.cloud.network_management_v1.types.VpcConnectorInfo): - Display information of a VPC connector. - - This field is a member of `oneof`_ ``step_info``. - deliver (google.cloud.network_management_v1.types.DeliverInfo): - Display information of the final state - "deliver" and reason. - - This field is a member of `oneof`_ ``step_info``. - forward (google.cloud.network_management_v1.types.ForwardInfo): - Display information of the final state - "forward" and reason. - - This field is a member of `oneof`_ ``step_info``. - abort (google.cloud.network_management_v1.types.AbortInfo): - Display information of the final state - "abort" and reason. - - This field is a member of `oneof`_ ``step_info``. - drop (google.cloud.network_management_v1.types.DropInfo): - Display information of the final state "drop" - and reason. - - This field is a member of `oneof`_ ``step_info``. - load_balancer (google.cloud.network_management_v1.types.LoadBalancerInfo): - Display information of the load balancers. Deprecated in - favor of the ``load_balancer_backend_info`` field, not used - in new tests. - - This field is a member of `oneof`_ ``step_info``. - network (google.cloud.network_management_v1.types.NetworkInfo): - Display information of a Google Cloud - network. - - This field is a member of `oneof`_ ``step_info``. - gke_master (google.cloud.network_management_v1.types.GKEMasterInfo): - Display information of a Google Kubernetes - Engine cluster master. - - This field is a member of `oneof`_ ``step_info``. - cloud_sql_instance (google.cloud.network_management_v1.types.CloudSQLInstanceInfo): - Display information of a Cloud SQL instance. - - This field is a member of `oneof`_ ``step_info``. - redis_instance (google.cloud.network_management_v1.types.RedisInstanceInfo): - Display information of a Redis Instance. - - This field is a member of `oneof`_ ``step_info``. - redis_cluster (google.cloud.network_management_v1.types.RedisClusterInfo): - Display information of a Redis Cluster. - - This field is a member of `oneof`_ ``step_info``. - cloud_function (google.cloud.network_management_v1.types.CloudFunctionInfo): - Display information of a Cloud Function. - - This field is a member of `oneof`_ ``step_info``. - app_engine_version (google.cloud.network_management_v1.types.AppEngineVersionInfo): - Display information of an App Engine service - version. - - This field is a member of `oneof`_ ``step_info``. - cloud_run_revision (google.cloud.network_management_v1.types.CloudRunRevisionInfo): - Display information of a Cloud Run revision. - - This field is a member of `oneof`_ ``step_info``. - nat (google.cloud.network_management_v1.types.NatInfo): - Display information of a NAT. - - This field is a member of `oneof`_ ``step_info``. - proxy_connection (google.cloud.network_management_v1.types.ProxyConnectionInfo): - Display information of a ProxyConnection. - - This field is a member of `oneof`_ ``step_info``. - load_balancer_backend_info (google.cloud.network_management_v1.types.LoadBalancerBackendInfo): - Display information of a specific load - balancer backend. - - This field is a member of `oneof`_ ``step_info``. - storage_bucket (google.cloud.network_management_v1.types.StorageBucketInfo): - Display information of a Storage Bucket. Used - only for return traces. - - This field is a member of `oneof`_ ``step_info``. - serverless_neg (google.cloud.network_management_v1.types.ServerlessNegInfo): - Display information of a Serverless network - endpoint group backend. Used only for return - traces. - - This field is a member of `oneof`_ ``step_info``. - """ - class State(proto.Enum): - r"""Type of states that are defined in the network state machine. - Each step in the packet trace is in a specific state. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - START_FROM_INSTANCE (1): - Initial state: packet originating from a - Compute Engine instance. An InstanceInfo is - populated with starting instance information. - START_FROM_INTERNET (2): - Initial state: packet originating from the - internet. The endpoint information is populated. - START_FROM_GOOGLE_SERVICE (27): - Initial state: packet originating from a Google service. The - google_service information is populated. - START_FROM_PRIVATE_NETWORK (3): - Initial state: packet originating from a VPC - or on-premises network with internal source IP. - If the source is a VPC network visible to the - user, a NetworkInfo is populated with details of - the network. - START_FROM_GKE_MASTER (21): - Initial state: packet originating from a - Google Kubernetes Engine cluster master. A - GKEMasterInfo is populated with starting - instance information. - START_FROM_CLOUD_SQL_INSTANCE (22): - Initial state: packet originating from a - Cloud SQL instance. A CloudSQLInstanceInfo is - populated with starting instance information. - START_FROM_REDIS_INSTANCE (32): - Initial state: packet originating from a - Redis instance. A RedisInstanceInfo is populated - with starting instance information. - START_FROM_REDIS_CLUSTER (33): - Initial state: packet originating from a - Redis Cluster. A RedisClusterInfo is populated - with starting Cluster information. - START_FROM_CLOUD_FUNCTION (23): - Initial state: packet originating from a - Cloud Function. A CloudFunctionInfo is populated - with starting function information. - START_FROM_APP_ENGINE_VERSION (25): - Initial state: packet originating from an App - Engine service version. An AppEngineVersionInfo - is populated with starting version information. - START_FROM_CLOUD_RUN_REVISION (26): - Initial state: packet originating from a - Cloud Run revision. A CloudRunRevisionInfo is - populated with starting revision information. - START_FROM_STORAGE_BUCKET (29): - Initial state: packet originating from a Storage Bucket. - Used only for return traces. The storage_bucket information - is populated. - START_FROM_PSC_PUBLISHED_SERVICE (30): - Initial state: packet originating from a - published service that uses Private Service - Connect. Used only for return traces. - START_FROM_SERVERLESS_NEG (31): - Initial state: packet originating from a serverless network - endpoint group backend. Used only for return traces. The - serverless_neg information is populated. - APPLY_INGRESS_FIREWALL_RULE (4): - Config checking state: verify ingress - firewall rule. - APPLY_EGRESS_FIREWALL_RULE (5): - Config checking state: verify egress firewall - rule. - APPLY_ROUTE (6): - Config checking state: verify route. - APPLY_FORWARDING_RULE (7): - Config checking state: match forwarding rule. - ANALYZE_LOAD_BALANCER_BACKEND (28): - Config checking state: verify load balancer - backend configuration. - SPOOFING_APPROVED (8): - Config checking state: packet sent or - received under foreign IP address and allowed. - ARRIVE_AT_INSTANCE (9): - Forwarding state: arriving at a Compute - Engine instance. - ARRIVE_AT_INTERNAL_LOAD_BALANCER (10): - Forwarding state: arriving at a Compute - Engine internal load balancer. - ARRIVE_AT_EXTERNAL_LOAD_BALANCER (11): - Forwarding state: arriving at a Compute - Engine external load balancer. - ARRIVE_AT_VPN_GATEWAY (12): - Forwarding state: arriving at a Cloud VPN - gateway. - ARRIVE_AT_VPN_TUNNEL (13): - Forwarding state: arriving at a Cloud VPN - tunnel. - ARRIVE_AT_VPC_CONNECTOR (24): - Forwarding state: arriving at a VPC - connector. - NAT (14): - Transition state: packet header translated. - PROXY_CONNECTION (15): - Transition state: original connection is - terminated and a new proxied connection is - initiated. - DELIVER (16): - Final state: packet could be delivered. - DROP (17): - Final state: packet could be dropped. - FORWARD (18): - Final state: packet could be forwarded to a - network with an unknown configuration. - ABORT (19): - Final state: analysis is aborted. - VIEWER_PERMISSION_MISSING (20): - Special state: viewer of the test result does - not have permission to see the configuration in - this step. - """ - STATE_UNSPECIFIED = 0 - START_FROM_INSTANCE = 1 - START_FROM_INTERNET = 2 - START_FROM_GOOGLE_SERVICE = 27 - START_FROM_PRIVATE_NETWORK = 3 - START_FROM_GKE_MASTER = 21 - START_FROM_CLOUD_SQL_INSTANCE = 22 - START_FROM_REDIS_INSTANCE = 32 - START_FROM_REDIS_CLUSTER = 33 - START_FROM_CLOUD_FUNCTION = 23 - START_FROM_APP_ENGINE_VERSION = 25 - START_FROM_CLOUD_RUN_REVISION = 26 - START_FROM_STORAGE_BUCKET = 29 - START_FROM_PSC_PUBLISHED_SERVICE = 30 - START_FROM_SERVERLESS_NEG = 31 - APPLY_INGRESS_FIREWALL_RULE = 4 - APPLY_EGRESS_FIREWALL_RULE = 5 - APPLY_ROUTE = 6 - APPLY_FORWARDING_RULE = 7 - ANALYZE_LOAD_BALANCER_BACKEND = 28 - SPOOFING_APPROVED = 8 - ARRIVE_AT_INSTANCE = 9 - ARRIVE_AT_INTERNAL_LOAD_BALANCER = 10 - ARRIVE_AT_EXTERNAL_LOAD_BALANCER = 11 - ARRIVE_AT_VPN_GATEWAY = 12 - ARRIVE_AT_VPN_TUNNEL = 13 - ARRIVE_AT_VPC_CONNECTOR = 24 - NAT = 14 - PROXY_CONNECTION = 15 - DELIVER = 16 - DROP = 17 - FORWARD = 18 - ABORT = 19 - VIEWER_PERMISSION_MISSING = 20 - - description: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - causes_drop: bool = proto.Field( - proto.BOOL, - number=3, - ) - project_id: str = proto.Field( - proto.STRING, - number=4, - ) - instance: 'InstanceInfo' = proto.Field( - proto.MESSAGE, - number=5, - oneof='step_info', - message='InstanceInfo', - ) - firewall: 'FirewallInfo' = proto.Field( - proto.MESSAGE, - number=6, - oneof='step_info', - message='FirewallInfo', - ) - route: 'RouteInfo' = proto.Field( - proto.MESSAGE, - number=7, - oneof='step_info', - message='RouteInfo', - ) - endpoint: 'EndpointInfo' = proto.Field( - proto.MESSAGE, - number=8, - oneof='step_info', - message='EndpointInfo', - ) - google_service: 'GoogleServiceInfo' = proto.Field( - proto.MESSAGE, - number=24, - oneof='step_info', - message='GoogleServiceInfo', - ) - forwarding_rule: 'ForwardingRuleInfo' = proto.Field( - proto.MESSAGE, - number=9, - oneof='step_info', - message='ForwardingRuleInfo', - ) - vpn_gateway: 'VpnGatewayInfo' = proto.Field( - proto.MESSAGE, - number=10, - oneof='step_info', - message='VpnGatewayInfo', - ) - vpn_tunnel: 'VpnTunnelInfo' = proto.Field( - proto.MESSAGE, - number=11, - oneof='step_info', - message='VpnTunnelInfo', - ) - vpc_connector: 'VpcConnectorInfo' = proto.Field( - proto.MESSAGE, - number=21, - oneof='step_info', - message='VpcConnectorInfo', - ) - deliver: 'DeliverInfo' = proto.Field( - proto.MESSAGE, - number=12, - oneof='step_info', - message='DeliverInfo', - ) - forward: 'ForwardInfo' = proto.Field( - proto.MESSAGE, - number=13, - oneof='step_info', - message='ForwardInfo', - ) - abort: 'AbortInfo' = proto.Field( - proto.MESSAGE, - number=14, - oneof='step_info', - message='AbortInfo', - ) - drop: 'DropInfo' = proto.Field( - proto.MESSAGE, - number=15, - oneof='step_info', - message='DropInfo', - ) - load_balancer: 'LoadBalancerInfo' = proto.Field( - proto.MESSAGE, - number=16, - oneof='step_info', - message='LoadBalancerInfo', - ) - network: 'NetworkInfo' = proto.Field( - proto.MESSAGE, - number=17, - oneof='step_info', - message='NetworkInfo', - ) - gke_master: 'GKEMasterInfo' = proto.Field( - proto.MESSAGE, - number=18, - oneof='step_info', - message='GKEMasterInfo', - ) - cloud_sql_instance: 'CloudSQLInstanceInfo' = proto.Field( - proto.MESSAGE, - number=19, - oneof='step_info', - message='CloudSQLInstanceInfo', - ) - redis_instance: 'RedisInstanceInfo' = proto.Field( - proto.MESSAGE, - number=30, - oneof='step_info', - message='RedisInstanceInfo', - ) - redis_cluster: 'RedisClusterInfo' = proto.Field( - proto.MESSAGE, - number=31, - oneof='step_info', - message='RedisClusterInfo', - ) - cloud_function: 'CloudFunctionInfo' = proto.Field( - proto.MESSAGE, - number=20, - oneof='step_info', - message='CloudFunctionInfo', - ) - app_engine_version: 'AppEngineVersionInfo' = proto.Field( - proto.MESSAGE, - number=22, - oneof='step_info', - message='AppEngineVersionInfo', - ) - cloud_run_revision: 'CloudRunRevisionInfo' = proto.Field( - proto.MESSAGE, - number=23, - oneof='step_info', - message='CloudRunRevisionInfo', - ) - nat: 'NatInfo' = proto.Field( - proto.MESSAGE, - number=25, - oneof='step_info', - message='NatInfo', - ) - proxy_connection: 'ProxyConnectionInfo' = proto.Field( - proto.MESSAGE, - number=26, - oneof='step_info', - message='ProxyConnectionInfo', - ) - load_balancer_backend_info: 'LoadBalancerBackendInfo' = proto.Field( - proto.MESSAGE, - number=27, - oneof='step_info', - message='LoadBalancerBackendInfo', - ) - storage_bucket: 'StorageBucketInfo' = proto.Field( - proto.MESSAGE, - number=28, - oneof='step_info', - message='StorageBucketInfo', - ) - serverless_neg: 'ServerlessNegInfo' = proto.Field( - proto.MESSAGE, - number=29, - oneof='step_info', - message='ServerlessNegInfo', - ) - - -class InstanceInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - instance. - - Attributes: - display_name (str): - Name of a Compute Engine instance. - uri (str): - URI of a Compute Engine instance. - interface (str): - Name of the network interface of a Compute - Engine instance. - network_uri (str): - URI of a Compute Engine network. - internal_ip (str): - Internal IP address of the network interface. - external_ip (str): - External IP address of the network interface. - network_tags (MutableSequence[str]): - Network tags configured on the instance. - service_account (str): - Service account authorized for the instance. - psc_network_attachment_uri (str): - URI of the PSC network attachment the NIC is - attached to (if relevant). - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - interface: str = proto.Field( - proto.STRING, - number=3, - ) - network_uri: str = proto.Field( - proto.STRING, - number=4, - ) - internal_ip: str = proto.Field( - proto.STRING, - number=5, - ) - external_ip: str = proto.Field( - proto.STRING, - number=6, - ) - network_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - service_account: str = proto.Field( - proto.STRING, - number=8, - ) - psc_network_attachment_uri: str = proto.Field( - proto.STRING, - number=9, - ) - - -class NetworkInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - network. Next ID: 7 - - Attributes: - display_name (str): - Name of a Compute Engine network. - uri (str): - URI of a Compute Engine network. - matched_subnet_uri (str): - URI of the subnet matching the source IP - address of the test. - matched_ip_range (str): - The IP range of the subnet matching the - source IP address of the test. - region (str): - The region of the subnet matching the source - IP address of the test. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - matched_subnet_uri: str = proto.Field( - proto.STRING, - number=5, - ) - matched_ip_range: str = proto.Field( - proto.STRING, - number=4, - ) - region: str = proto.Field( - proto.STRING, - number=6, - ) - - -class FirewallInfo(proto.Message): - r"""For display only. Metadata associated with a VPC firewall - rule, an implied VPC firewall rule, or a firewall policy rule. - - Attributes: - display_name (str): - The display name of the firewall rule. This - field might be empty for firewall policy rules. - uri (str): - The URI of the firewall rule. This field is - not applicable to implied VPC firewall rules. - direction (str): - Possible values: INGRESS, EGRESS - action (str): - Possible values: ALLOW, DENY, APPLY_SECURITY_PROFILE_GROUP - priority (int): - The priority of the firewall rule. - network_uri (str): - The URI of the VPC network that the firewall - rule is associated with. This field is not - applicable to hierarchical firewall policy - rules. - target_tags (MutableSequence[str]): - The target tags defined by the VPC firewall - rule. This field is not applicable to firewall - policy rules. - target_service_accounts (MutableSequence[str]): - The target service accounts specified by the - firewall rule. - policy (str): - The name of the firewall policy that this - rule is associated with. This field is not - applicable to VPC firewall rules and implied VPC - firewall rules. - policy_uri (str): - The URI of the firewall policy that this rule - is associated with. This field is not applicable - to VPC firewall rules and implied VPC firewall - rules. - firewall_rule_type (google.cloud.network_management_v1.types.FirewallInfo.FirewallRuleType): - The firewall rule's type. - """ - class FirewallRuleType(proto.Enum): - r"""The firewall rule's type. - - Values: - FIREWALL_RULE_TYPE_UNSPECIFIED (0): - Unspecified type. - HIERARCHICAL_FIREWALL_POLICY_RULE (1): - Hierarchical firewall policy rule. For details, see - `Hierarchical firewall policies - overview `__. - VPC_FIREWALL_RULE (2): - VPC firewall rule. For details, see `VPC firewall rules - overview `__. - IMPLIED_VPC_FIREWALL_RULE (3): - Implied VPC firewall rule. For details, see `Implied - rules `__. - SERVERLESS_VPC_ACCESS_MANAGED_FIREWALL_RULE (4): - Implicit firewall rules that are managed by serverless VPC - access to allow ingress access. They are not visible in the - Google Cloud console. For details, see `VPC connector's - implicit - rules `__. - NETWORK_FIREWALL_POLICY_RULE (5): - Global network firewall policy rule. For details, see - `Network firewall - policies `__. - NETWORK_REGIONAL_FIREWALL_POLICY_RULE (6): - Regional network firewall policy rule. For details, see - `Regional network firewall - policies `__. - UNSUPPORTED_FIREWALL_POLICY_RULE (100): - Firewall policy rule containing attributes not yet supported - in Connectivity tests. Firewall analysis is skipped if such - a rule can potentially be matched. Please see the `list of - unsupported - configurations `__. - TRACKING_STATE (101): - Tracking state for response traffic created when request - traffic goes through allow firewall rule. For details, see - `firewall rules - specifications `__ - """ - FIREWALL_RULE_TYPE_UNSPECIFIED = 0 - HIERARCHICAL_FIREWALL_POLICY_RULE = 1 - VPC_FIREWALL_RULE = 2 - IMPLIED_VPC_FIREWALL_RULE = 3 - SERVERLESS_VPC_ACCESS_MANAGED_FIREWALL_RULE = 4 - NETWORK_FIREWALL_POLICY_RULE = 5 - NETWORK_REGIONAL_FIREWALL_POLICY_RULE = 6 - UNSUPPORTED_FIREWALL_POLICY_RULE = 100 - TRACKING_STATE = 101 - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - direction: str = proto.Field( - proto.STRING, - number=3, - ) - action: str = proto.Field( - proto.STRING, - number=4, - ) - priority: int = proto.Field( - proto.INT32, - number=5, - ) - network_uri: str = proto.Field( - proto.STRING, - number=6, - ) - target_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - target_service_accounts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - policy: str = proto.Field( - proto.STRING, - number=9, - ) - policy_uri: str = proto.Field( - proto.STRING, - number=11, - ) - firewall_rule_type: FirewallRuleType = proto.Field( - proto.ENUM, - number=10, - enum=FirewallRuleType, - ) - - -class RouteInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - route. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - route_type (google.cloud.network_management_v1.types.RouteInfo.RouteType): - Type of route. - next_hop_type (google.cloud.network_management_v1.types.RouteInfo.NextHopType): - Type of next hop. - route_scope (google.cloud.network_management_v1.types.RouteInfo.RouteScope): - Indicates where route is applicable. - display_name (str): - Name of a route. - uri (str): - URI of a route (if applicable). - region (str): - Region of the route (if applicable). - dest_ip_range (str): - Destination IP range of the route. - next_hop (str): - Next hop of the route. - network_uri (str): - URI of a Compute Engine network. NETWORK - routes only. - priority (int): - Priority of the route. - instance_tags (MutableSequence[str]): - Instance tags of the route. - src_ip_range (str): - Source IP address range of the route. Policy - based routes only. - dest_port_ranges (MutableSequence[str]): - Destination port ranges of the route. Policy - based routes only. - src_port_ranges (MutableSequence[str]): - Source port ranges of the route. Policy based - routes only. - protocols (MutableSequence[str]): - Protocols of the route. Policy based routes - only. - ncc_hub_uri (str): - URI of a NCC Hub. NCC_HUB routes only. - - This field is a member of `oneof`_ ``_ncc_hub_uri``. - ncc_spoke_uri (str): - URI of a NCC Spoke. NCC_HUB routes only. - - This field is a member of `oneof`_ ``_ncc_spoke_uri``. - advertised_route_source_router_uri (str): - For advertised dynamic routes, the URI of the - Cloud Router that advertised the corresponding - IP prefix. - - This field is a member of `oneof`_ ``_advertised_route_source_router_uri``. - advertised_route_next_hop_uri (str): - For advertised routes, the URI of their next - hop, i.e. the URI of the hybrid endpoint (VPN - tunnel, Interconnect attachment, NCC router - appliance) the advertised prefix is advertised - through, or URI of the source peered network. - - This field is a member of `oneof`_ ``_advertised_route_next_hop_uri``. - """ - class RouteType(proto.Enum): - r"""Type of route: - - Values: - ROUTE_TYPE_UNSPECIFIED (0): - Unspecified type. Default value. - SUBNET (1): - Route is a subnet route automatically created - by the system. - STATIC (2): - Static route created by the user, including - the default route to the internet. - DYNAMIC (3): - Dynamic route exchanged between BGP peers. - PEERING_SUBNET (4): - A subnet route received from peering network. - PEERING_STATIC (5): - A static route received from peering network. - PEERING_DYNAMIC (6): - A dynamic route received from peering - network. - POLICY_BASED (7): - Policy based route. - ADVERTISED (101): - Advertised route. Synthetic route which is - used to transition from the - StartFromPrivateNetwork state in Connectivity - tests. - """ - ROUTE_TYPE_UNSPECIFIED = 0 - SUBNET = 1 - STATIC = 2 - DYNAMIC = 3 - PEERING_SUBNET = 4 - PEERING_STATIC = 5 - PEERING_DYNAMIC = 6 - POLICY_BASED = 7 - ADVERTISED = 101 - - class NextHopType(proto.Enum): - r"""Type of next hop: - - Values: - NEXT_HOP_TYPE_UNSPECIFIED (0): - Unspecified type. Default value. - NEXT_HOP_IP (1): - Next hop is an IP address. - NEXT_HOP_INSTANCE (2): - Next hop is a Compute Engine instance. - NEXT_HOP_NETWORK (3): - Next hop is a VPC network gateway. - NEXT_HOP_PEERING (4): - Next hop is a peering VPC. - NEXT_HOP_INTERCONNECT (5): - Next hop is an interconnect. - NEXT_HOP_VPN_TUNNEL (6): - Next hop is a VPN tunnel. - NEXT_HOP_VPN_GATEWAY (7): - Next hop is a VPN gateway. This scenario only - happens when tracing connectivity from an - on-premises network to Google Cloud through a - VPN. The analysis simulates a packet departing - from the on-premises network through a VPN - tunnel and arriving at a Cloud VPN gateway. - NEXT_HOP_INTERNET_GATEWAY (8): - Next hop is an internet gateway. - NEXT_HOP_BLACKHOLE (9): - Next hop is blackhole; that is, the next hop - either does not exist or is not running. - NEXT_HOP_ILB (10): - Next hop is the forwarding rule of an - Internal Load Balancer. - NEXT_HOP_ROUTER_APPLIANCE (11): - Next hop is a `router appliance - instance `__. - NEXT_HOP_NCC_HUB (12): - Next hop is an NCC hub. - """ - NEXT_HOP_TYPE_UNSPECIFIED = 0 - NEXT_HOP_IP = 1 - NEXT_HOP_INSTANCE = 2 - NEXT_HOP_NETWORK = 3 - NEXT_HOP_PEERING = 4 - NEXT_HOP_INTERCONNECT = 5 - NEXT_HOP_VPN_TUNNEL = 6 - NEXT_HOP_VPN_GATEWAY = 7 - NEXT_HOP_INTERNET_GATEWAY = 8 - NEXT_HOP_BLACKHOLE = 9 - NEXT_HOP_ILB = 10 - NEXT_HOP_ROUTER_APPLIANCE = 11 - NEXT_HOP_NCC_HUB = 12 - - class RouteScope(proto.Enum): - r"""Indicates where routes are applicable. - - Values: - ROUTE_SCOPE_UNSPECIFIED (0): - Unspecified scope. Default value. - NETWORK (1): - Route is applicable to packets in Network. - NCC_HUB (2): - Route is applicable to packets using NCC - Hub's routing table. - """ - ROUTE_SCOPE_UNSPECIFIED = 0 - NETWORK = 1 - NCC_HUB = 2 - - route_type: RouteType = proto.Field( - proto.ENUM, - number=8, - enum=RouteType, - ) - next_hop_type: NextHopType = proto.Field( - proto.ENUM, - number=9, - enum=NextHopType, - ) - route_scope: RouteScope = proto.Field( - proto.ENUM, - number=14, - enum=RouteScope, - ) - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - region: str = proto.Field( - proto.STRING, - number=19, - ) - dest_ip_range: str = proto.Field( - proto.STRING, - number=3, - ) - next_hop: str = proto.Field( - proto.STRING, - number=4, - ) - network_uri: str = proto.Field( - proto.STRING, - number=5, - ) - priority: int = proto.Field( - proto.INT32, - number=6, - ) - instance_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - src_ip_range: str = proto.Field( - proto.STRING, - number=10, - ) - dest_port_ranges: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=11, - ) - src_port_ranges: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=12, - ) - protocols: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=13, - ) - ncc_hub_uri: str = proto.Field( - proto.STRING, - number=15, - optional=True, - ) - ncc_spoke_uri: str = proto.Field( - proto.STRING, - number=16, - optional=True, - ) - advertised_route_source_router_uri: str = proto.Field( - proto.STRING, - number=17, - optional=True, - ) - advertised_route_next_hop_uri: str = proto.Field( - proto.STRING, - number=18, - optional=True, - ) - - -class GoogleServiceInfo(proto.Message): - r"""For display only. Details of a Google Service sending packets to a - VPC network. Although the source IP might be a publicly routable - address, some Google Services use special routes within Google - production infrastructure to reach Compute Engine Instances. - https://cloud.google.com/vpc/docs/routes#special_return_paths - - Attributes: - source_ip (str): - Source IP address. - google_service_type (google.cloud.network_management_v1.types.GoogleServiceInfo.GoogleServiceType): - Recognized type of a Google Service. - """ - class GoogleServiceType(proto.Enum): - r"""Recognized type of a Google Service. - - Values: - GOOGLE_SERVICE_TYPE_UNSPECIFIED (0): - Unspecified Google Service. - IAP (1): - Identity aware proxy. - https://cloud.google.com/iap/docs/using-tcp-forwarding - GFE_PROXY_OR_HEALTH_CHECK_PROBER (2): - One of two services sharing IP ranges: - - - Load Balancer proxy - - Centralized Health Check prober - https://cloud.google.com/load-balancing/docs/firewall-rules - CLOUD_DNS (3): - Connectivity from Cloud DNS to forwarding - targets or alternate name servers that use - private routing. - https://cloud.google.com/dns/docs/zones/forwarding-zones#firewall-rules - https://cloud.google.com/dns/docs/policies#firewall-rules - GOOGLE_API (4): - private.googleapis.com and - restricted.googleapis.com - GOOGLE_API_PSC (5): - Google API via Private Service Connect. - https://cloud.google.com/vpc/docs/configure-private-service-connect-apis - GOOGLE_API_VPC_SC (6): - Google API via VPC Service Controls. - https://cloud.google.com/vpc/docs/configure-private-service-connect-apis - """ - GOOGLE_SERVICE_TYPE_UNSPECIFIED = 0 - IAP = 1 - GFE_PROXY_OR_HEALTH_CHECK_PROBER = 2 - CLOUD_DNS = 3 - GOOGLE_API = 4 - GOOGLE_API_PSC = 5 - GOOGLE_API_VPC_SC = 6 - - source_ip: str = proto.Field( - proto.STRING, - number=1, - ) - google_service_type: GoogleServiceType = proto.Field( - proto.ENUM, - number=2, - enum=GoogleServiceType, - ) - - -class ForwardingRuleInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - forwarding rule. - - Attributes: - display_name (str): - Name of the forwarding rule. - uri (str): - URI of the forwarding rule. - matched_protocol (str): - Protocol defined in the forwarding rule that - matches the packet. - matched_port_range (str): - Port range defined in the forwarding rule - that matches the packet. - vip (str): - VIP of the forwarding rule. - target (str): - Target type of the forwarding rule. - network_uri (str): - Network URI. - region (str): - Region of the forwarding rule. Set only for - regional forwarding rules. - load_balancer_name (str): - Name of the load balancer the forwarding rule - belongs to. Empty for forwarding rules not - related to load balancers (like PSC forwarding - rules). - psc_service_attachment_uri (str): - URI of the PSC service attachment this - forwarding rule targets (if applicable). - psc_google_api_target (str): - PSC Google API target this forwarding rule - targets (if applicable). - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - matched_protocol: str = proto.Field( - proto.STRING, - number=3, - ) - matched_port_range: str = proto.Field( - proto.STRING, - number=6, - ) - vip: str = proto.Field( - proto.STRING, - number=4, - ) - target: str = proto.Field( - proto.STRING, - number=5, - ) - network_uri: str = proto.Field( - proto.STRING, - number=7, - ) - region: str = proto.Field( - proto.STRING, - number=8, - ) - load_balancer_name: str = proto.Field( - proto.STRING, - number=9, - ) - psc_service_attachment_uri: str = proto.Field( - proto.STRING, - number=10, - ) - psc_google_api_target: str = proto.Field( - proto.STRING, - number=11, - ) - - -class LoadBalancerInfo(proto.Message): - r"""For display only. Metadata associated with a load balancer. - - Attributes: - load_balancer_type (google.cloud.network_management_v1.types.LoadBalancerInfo.LoadBalancerType): - Type of the load balancer. - health_check_uri (str): - URI of the health check for the load - balancer. Deprecated and no longer populated as - different load balancer backends might have - different health checks. - backends (MutableSequence[google.cloud.network_management_v1.types.LoadBalancerBackend]): - Information for the loadbalancer backends. - backend_type (google.cloud.network_management_v1.types.LoadBalancerInfo.BackendType): - Type of load balancer's backend - configuration. - backend_uri (str): - Backend configuration URI. - """ - class LoadBalancerType(proto.Enum): - r"""The type definition for a load balancer: - - Values: - LOAD_BALANCER_TYPE_UNSPECIFIED (0): - Type is unspecified. - INTERNAL_TCP_UDP (1): - Internal TCP/UDP load balancer. - NETWORK_TCP_UDP (2): - Network TCP/UDP load balancer. - HTTP_PROXY (3): - HTTP(S) proxy load balancer. - TCP_PROXY (4): - TCP proxy load balancer. - SSL_PROXY (5): - SSL proxy load balancer. - """ - LOAD_BALANCER_TYPE_UNSPECIFIED = 0 - INTERNAL_TCP_UDP = 1 - NETWORK_TCP_UDP = 2 - HTTP_PROXY = 3 - TCP_PROXY = 4 - SSL_PROXY = 5 - - class BackendType(proto.Enum): - r"""The type definition for a load balancer backend - configuration: - - Values: - BACKEND_TYPE_UNSPECIFIED (0): - Type is unspecified. - BACKEND_SERVICE (1): - Backend Service as the load balancer's - backend. - TARGET_POOL (2): - Target Pool as the load balancer's backend. - TARGET_INSTANCE (3): - Target Instance as the load balancer's - backend. - """ - BACKEND_TYPE_UNSPECIFIED = 0 - BACKEND_SERVICE = 1 - TARGET_POOL = 2 - TARGET_INSTANCE = 3 - - load_balancer_type: LoadBalancerType = proto.Field( - proto.ENUM, - number=1, - enum=LoadBalancerType, - ) - health_check_uri: str = proto.Field( - proto.STRING, - number=2, - ) - backends: MutableSequence['LoadBalancerBackend'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LoadBalancerBackend', - ) - backend_type: BackendType = proto.Field( - proto.ENUM, - number=4, - enum=BackendType, - ) - backend_uri: str = proto.Field( - proto.STRING, - number=5, - ) - - -class LoadBalancerBackend(proto.Message): - r"""For display only. Metadata associated with a specific load - balancer backend. - - Attributes: - display_name (str): - Name of a Compute Engine instance or network - endpoint. - uri (str): - URI of a Compute Engine instance or network - endpoint. - health_check_firewall_state (google.cloud.network_management_v1.types.LoadBalancerBackend.HealthCheckFirewallState): - State of the health check firewall - configuration. - health_check_allowing_firewall_rules (MutableSequence[str]): - A list of firewall rule URIs allowing probes - from health check IP ranges. - health_check_blocking_firewall_rules (MutableSequence[str]): - A list of firewall rule URIs blocking probes - from health check IP ranges. - """ - class HealthCheckFirewallState(proto.Enum): - r"""State of a health check firewall configuration: - - Values: - HEALTH_CHECK_FIREWALL_STATE_UNSPECIFIED (0): - State is unspecified. Default state if not - populated. - CONFIGURED (1): - There are configured firewall rules to allow - health check probes to the backend. - MISCONFIGURED (2): - There are firewall rules configured to allow - partial health check ranges or block all health - check ranges. If a health check probe is sent - from denied IP ranges, the health check to the - backend will fail. Then, the backend will be - marked unhealthy and will not receive traffic - sent to the load balancer. - """ - HEALTH_CHECK_FIREWALL_STATE_UNSPECIFIED = 0 - CONFIGURED = 1 - MISCONFIGURED = 2 - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - health_check_firewall_state: HealthCheckFirewallState = proto.Field( - proto.ENUM, - number=3, - enum=HealthCheckFirewallState, - ) - health_check_allowing_firewall_rules: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - health_check_blocking_firewall_rules: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - - -class VpnGatewayInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - VPN gateway. - - Attributes: - display_name (str): - Name of a VPN gateway. - uri (str): - URI of a VPN gateway. - network_uri (str): - URI of a Compute Engine network where the VPN - gateway is configured. - ip_address (str): - IP address of the VPN gateway. - vpn_tunnel_uri (str): - A VPN tunnel that is associated with this VPN - gateway. There may be multiple VPN tunnels - configured on a VPN gateway, and only the one - relevant to the test is displayed. - region (str): - Name of a Google Cloud region where this VPN - gateway is configured. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - network_uri: str = proto.Field( - proto.STRING, - number=3, - ) - ip_address: str = proto.Field( - proto.STRING, - number=4, - ) - vpn_tunnel_uri: str = proto.Field( - proto.STRING, - number=5, - ) - region: str = proto.Field( - proto.STRING, - number=6, - ) - - -class VpnTunnelInfo(proto.Message): - r"""For display only. Metadata associated with a Compute Engine - VPN tunnel. - - Attributes: - display_name (str): - Name of a VPN tunnel. - uri (str): - URI of a VPN tunnel. - source_gateway (str): - URI of the VPN gateway at local end of the - tunnel. - remote_gateway (str): - URI of a VPN gateway at remote end of the - tunnel. - remote_gateway_ip (str): - Remote VPN gateway's IP address. - source_gateway_ip (str): - Local VPN gateway's IP address. - network_uri (str): - URI of a Compute Engine network where the VPN - tunnel is configured. - region (str): - Name of a Google Cloud region where this VPN - tunnel is configured. - routing_type (google.cloud.network_management_v1.types.VpnTunnelInfo.RoutingType): - Type of the routing policy. - """ - class RoutingType(proto.Enum): - r"""Types of VPN routing policy. For details, refer to `Networks and - Tunnel - routing `__. - - Values: - ROUTING_TYPE_UNSPECIFIED (0): - Unspecified type. Default value. - ROUTE_BASED (1): - Route based VPN. - POLICY_BASED (2): - Policy based routing. - DYNAMIC (3): - Dynamic (BGP) routing. - """ - ROUTING_TYPE_UNSPECIFIED = 0 - ROUTE_BASED = 1 - POLICY_BASED = 2 - DYNAMIC = 3 - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - source_gateway: str = proto.Field( - proto.STRING, - number=3, - ) - remote_gateway: str = proto.Field( - proto.STRING, - number=4, - ) - remote_gateway_ip: str = proto.Field( - proto.STRING, - number=5, - ) - source_gateway_ip: str = proto.Field( - proto.STRING, - number=6, - ) - network_uri: str = proto.Field( - proto.STRING, - number=7, - ) - region: str = proto.Field( - proto.STRING, - number=8, - ) - routing_type: RoutingType = proto.Field( - proto.ENUM, - number=9, - enum=RoutingType, - ) - - -class EndpointInfo(proto.Message): - r"""For display only. The specification of the endpoints for the - test. EndpointInfo is derived from source and destination - Endpoint and validated by the backend data plane model. - - Attributes: - source_ip (str): - Source IP address. - destination_ip (str): - Destination IP address. - protocol (str): - IP protocol in string format, for example: - "TCP", "UDP", "ICMP". - source_port (int): - Source port. Only valid when protocol is TCP - or UDP. - destination_port (int): - Destination port. Only valid when protocol is - TCP or UDP. - source_network_uri (str): - URI of the network where this packet - originates from. - destination_network_uri (str): - URI of the network where this packet is sent - to. - source_agent_uri (str): - URI of the source telemetry agent this packet - originates from. - """ - - source_ip: str = proto.Field( - proto.STRING, - number=1, - ) - destination_ip: str = proto.Field( - proto.STRING, - number=2, - ) - protocol: str = proto.Field( - proto.STRING, - number=3, - ) - source_port: int = proto.Field( - proto.INT32, - number=4, - ) - destination_port: int = proto.Field( - proto.INT32, - number=5, - ) - source_network_uri: str = proto.Field( - proto.STRING, - number=6, - ) - destination_network_uri: str = proto.Field( - proto.STRING, - number=7, - ) - source_agent_uri: str = proto.Field( - proto.STRING, - number=8, - ) - - -class DeliverInfo(proto.Message): - r"""Details of the final state "deliver" and associated resource. - - Attributes: - target (google.cloud.network_management_v1.types.DeliverInfo.Target): - Target type where the packet is delivered to. - resource_uri (str): - URI of the resource that the packet is - delivered to. - ip_address (str): - IP address of the target (if applicable). - storage_bucket (str): - Name of the Cloud Storage Bucket the packet - is delivered to (if applicable). - psc_google_api_target (str): - PSC Google API target the packet is delivered - to (if applicable). - """ - class Target(proto.Enum): - r"""Deliver target types: - - Values: - TARGET_UNSPECIFIED (0): - Target not specified. - INSTANCE (1): - Target is a Compute Engine instance. - INTERNET (2): - Target is the internet. - GOOGLE_API (3): - Target is a Google API. - GKE_MASTER (4): - Target is a Google Kubernetes Engine cluster - master. - CLOUD_SQL_INSTANCE (5): - Target is a Cloud SQL instance. - PSC_PUBLISHED_SERVICE (6): - Target is a published service that uses `Private Service - Connect `__. - PSC_GOOGLE_API (7): - Target is Google APIs that use `Private Service - Connect `__. - PSC_VPC_SC (8): - Target is a VPC-SC that uses `Private Service - Connect `__. - SERVERLESS_NEG (9): - Target is a serverless network endpoint - group. - STORAGE_BUCKET (10): - Target is a Cloud Storage bucket. - PRIVATE_NETWORK (11): - Target is a private network. Used only for - return traces. - CLOUD_FUNCTION (12): - Target is a Cloud Function. Used only for - return traces. - APP_ENGINE_VERSION (13): - Target is a App Engine service version. Used - only for return traces. - CLOUD_RUN_REVISION (14): - Target is a Cloud Run revision. Used only for - return traces. - GOOGLE_MANAGED_SERVICE (15): - Target is a Google-managed service. Used only - for return traces. - REDIS_INSTANCE (16): - Target is a Redis Instance. - REDIS_CLUSTER (17): - Target is a Redis Cluster. - """ - TARGET_UNSPECIFIED = 0 - INSTANCE = 1 - INTERNET = 2 - GOOGLE_API = 3 - GKE_MASTER = 4 - CLOUD_SQL_INSTANCE = 5 - PSC_PUBLISHED_SERVICE = 6 - PSC_GOOGLE_API = 7 - PSC_VPC_SC = 8 - SERVERLESS_NEG = 9 - STORAGE_BUCKET = 10 - PRIVATE_NETWORK = 11 - CLOUD_FUNCTION = 12 - APP_ENGINE_VERSION = 13 - CLOUD_RUN_REVISION = 14 - GOOGLE_MANAGED_SERVICE = 15 - REDIS_INSTANCE = 16 - REDIS_CLUSTER = 17 - - target: Target = proto.Field( - proto.ENUM, - number=1, - enum=Target, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=2, - ) - ip_address: str = proto.Field( - proto.STRING, - number=3, - ) - storage_bucket: str = proto.Field( - proto.STRING, - number=4, - ) - psc_google_api_target: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ForwardInfo(proto.Message): - r"""Details of the final state "forward" and associated resource. - - Attributes: - target (google.cloud.network_management_v1.types.ForwardInfo.Target): - Target type where this packet is forwarded - to. - resource_uri (str): - URI of the resource that the packet is - forwarded to. - ip_address (str): - IP address of the target (if applicable). - """ - class Target(proto.Enum): - r"""Forward target types. - - Values: - TARGET_UNSPECIFIED (0): - Target not specified. - PEERING_VPC (1): - Forwarded to a VPC peering network. - VPN_GATEWAY (2): - Forwarded to a Cloud VPN gateway. - INTERCONNECT (3): - Forwarded to a Cloud Interconnect connection. - GKE_MASTER (4): - Forwarded to a Google Kubernetes Engine - Container cluster master. - IMPORTED_CUSTOM_ROUTE_NEXT_HOP (5): - Forwarded to the next hop of a custom route - imported from a peering VPC. - CLOUD_SQL_INSTANCE (6): - Forwarded to a Cloud SQL instance. - ANOTHER_PROJECT (7): - Forwarded to a VPC network in another - project. - NCC_HUB (8): - Forwarded to an NCC Hub. - ROUTER_APPLIANCE (9): - Forwarded to a router appliance. - """ - TARGET_UNSPECIFIED = 0 - PEERING_VPC = 1 - VPN_GATEWAY = 2 - INTERCONNECT = 3 - GKE_MASTER = 4 - IMPORTED_CUSTOM_ROUTE_NEXT_HOP = 5 - CLOUD_SQL_INSTANCE = 6 - ANOTHER_PROJECT = 7 - NCC_HUB = 8 - ROUTER_APPLIANCE = 9 - - target: Target = proto.Field( - proto.ENUM, - number=1, - enum=Target, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=2, - ) - ip_address: str = proto.Field( - proto.STRING, - number=3, - ) - - -class AbortInfo(proto.Message): - r"""Details of the final state "abort" and associated resource. - - Attributes: - cause (google.cloud.network_management_v1.types.AbortInfo.Cause): - Causes that the analysis is aborted. - resource_uri (str): - URI of the resource that caused the abort. - ip_address (str): - IP address that caused the abort. - projects_missing_permission (MutableSequence[str]): - List of project IDs the user specified in the request but - lacks access to. In this case, analysis is aborted with the - PERMISSION_DENIED cause. - """ - class Cause(proto.Enum): - r"""Abort cause types: - - Values: - CAUSE_UNSPECIFIED (0): - Cause is unspecified. - UNKNOWN_NETWORK (1): - Aborted due to unknown network. Deprecated, - not used in the new tests. - UNKNOWN_PROJECT (3): - Aborted because no project information can be - derived from the test input. Deprecated, not - used in the new tests. - NO_EXTERNAL_IP (7): - Aborted because traffic is sent from a public - IP to an instance without an external IP. - Deprecated, not used in the new tests. - UNINTENDED_DESTINATION (8): - Aborted because none of the traces matches - destination information specified in the input - test request. Deprecated, not used in the new - tests. - SOURCE_ENDPOINT_NOT_FOUND (11): - Aborted because the source endpoint could not - be found. Deprecated, not used in the new tests. - MISMATCHED_SOURCE_NETWORK (12): - Aborted because the source network does not - match the source endpoint. Deprecated, not used - in the new tests. - DESTINATION_ENDPOINT_NOT_FOUND (13): - Aborted because the destination endpoint - could not be found. Deprecated, not used in the - new tests. - MISMATCHED_DESTINATION_NETWORK (14): - Aborted because the destination network does - not match the destination endpoint. Deprecated, - not used in the new tests. - UNKNOWN_IP (2): - Aborted because no endpoint with the packet's - destination IP address is found. - GOOGLE_MANAGED_SERVICE_UNKNOWN_IP (32): - Aborted because no endpoint with the packet's - destination IP is found in the Google-managed - project. - SOURCE_IP_ADDRESS_NOT_IN_SOURCE_NETWORK (23): - Aborted because the source IP address doesn't - belong to any of the subnets of the source VPC - network. - PERMISSION_DENIED (4): - Aborted because user lacks permission to - access all or part of the network configurations - required to run the test. - PERMISSION_DENIED_NO_CLOUD_NAT_CONFIGS (28): - Aborted because user lacks permission to - access Cloud NAT configs required to run the - test. - PERMISSION_DENIED_NO_NEG_ENDPOINT_CONFIGS (29): - Aborted because user lacks permission to - access Network endpoint group endpoint configs - required to run the test. - PERMISSION_DENIED_NO_CLOUD_ROUTER_CONFIGS (36): - Aborted because user lacks permission to - access Cloud Router configs required to run the - test. - NO_SOURCE_LOCATION (5): - Aborted because no valid source or - destination endpoint is derived from the input - test request. - INVALID_ARGUMENT (6): - Aborted because the source or destination - endpoint specified in the request is invalid. - Some examples: - - - The request might contain malformed resource - URI, project ID, or IP address. - - The request might contain inconsistent - information (for example, the request might - include both the instance and the network, but - the instance might not have a NIC in that - network). - TRACE_TOO_LONG (9): - Aborted because the number of steps in the - trace exceeds a certain limit. It might be - caused by a routing loop. - INTERNAL_ERROR (10): - Aborted due to internal server error. - UNSUPPORTED (15): - Aborted because the test scenario is not - supported. - MISMATCHED_IP_VERSION (16): - Aborted because the source and destination - resources have no common IP version. - GKE_KONNECTIVITY_PROXY_UNSUPPORTED (17): - Aborted because the connection between the - control plane and the node of the source cluster - is initiated by the node and managed by the - Konnectivity proxy. - RESOURCE_CONFIG_NOT_FOUND (18): - Aborted because expected resource - configuration was missing. - VM_INSTANCE_CONFIG_NOT_FOUND (24): - Aborted because expected VM instance - configuration was missing. - NETWORK_CONFIG_NOT_FOUND (25): - Aborted because expected network - configuration was missing. - FIREWALL_CONFIG_NOT_FOUND (26): - Aborted because expected firewall - configuration was missing. - ROUTE_CONFIG_NOT_FOUND (27): - Aborted because expected route configuration - was missing. - GOOGLE_MANAGED_SERVICE_AMBIGUOUS_PSC_ENDPOINT (19): - Aborted because a PSC endpoint selection for - the Google-managed service is ambiguous (several - PSC endpoints satisfy test input). - SOURCE_PSC_CLOUD_SQL_UNSUPPORTED (20): - Aborted because tests with a PSC-based Cloud - SQL instance as a source are not supported. - SOURCE_REDIS_CLUSTER_UNSUPPORTED (34): - Aborted because tests with a Redis Cluster as - a source are not supported. - SOURCE_REDIS_INSTANCE_UNSUPPORTED (35): - Aborted because tests with a Redis Instance - as a source are not supported. - SOURCE_FORWARDING_RULE_UNSUPPORTED (21): - Aborted because tests with a forwarding rule - as a source are not supported. - NON_ROUTABLE_IP_ADDRESS (22): - Aborted because one of the endpoints is a - non-routable IP address (loopback, link-local, - etc). - UNKNOWN_ISSUE_IN_GOOGLE_MANAGED_PROJECT (30): - Aborted due to an unknown issue in the - Google-managed project. - UNSUPPORTED_GOOGLE_MANAGED_PROJECT_CONFIG (31): - Aborted due to an unsupported configuration - of the Google-managed project. - """ - CAUSE_UNSPECIFIED = 0 - UNKNOWN_NETWORK = 1 - UNKNOWN_PROJECT = 3 - NO_EXTERNAL_IP = 7 - UNINTENDED_DESTINATION = 8 - SOURCE_ENDPOINT_NOT_FOUND = 11 - MISMATCHED_SOURCE_NETWORK = 12 - DESTINATION_ENDPOINT_NOT_FOUND = 13 - MISMATCHED_DESTINATION_NETWORK = 14 - UNKNOWN_IP = 2 - GOOGLE_MANAGED_SERVICE_UNKNOWN_IP = 32 - SOURCE_IP_ADDRESS_NOT_IN_SOURCE_NETWORK = 23 - PERMISSION_DENIED = 4 - PERMISSION_DENIED_NO_CLOUD_NAT_CONFIGS = 28 - PERMISSION_DENIED_NO_NEG_ENDPOINT_CONFIGS = 29 - PERMISSION_DENIED_NO_CLOUD_ROUTER_CONFIGS = 36 - NO_SOURCE_LOCATION = 5 - INVALID_ARGUMENT = 6 - TRACE_TOO_LONG = 9 - INTERNAL_ERROR = 10 - UNSUPPORTED = 15 - MISMATCHED_IP_VERSION = 16 - GKE_KONNECTIVITY_PROXY_UNSUPPORTED = 17 - RESOURCE_CONFIG_NOT_FOUND = 18 - VM_INSTANCE_CONFIG_NOT_FOUND = 24 - NETWORK_CONFIG_NOT_FOUND = 25 - FIREWALL_CONFIG_NOT_FOUND = 26 - ROUTE_CONFIG_NOT_FOUND = 27 - GOOGLE_MANAGED_SERVICE_AMBIGUOUS_PSC_ENDPOINT = 19 - SOURCE_PSC_CLOUD_SQL_UNSUPPORTED = 20 - SOURCE_REDIS_CLUSTER_UNSUPPORTED = 34 - SOURCE_REDIS_INSTANCE_UNSUPPORTED = 35 - SOURCE_FORWARDING_RULE_UNSUPPORTED = 21 - NON_ROUTABLE_IP_ADDRESS = 22 - UNKNOWN_ISSUE_IN_GOOGLE_MANAGED_PROJECT = 30 - UNSUPPORTED_GOOGLE_MANAGED_PROJECT_CONFIG = 31 - - cause: Cause = proto.Field( - proto.ENUM, - number=1, - enum=Cause, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=2, - ) - ip_address: str = proto.Field( - proto.STRING, - number=4, - ) - projects_missing_permission: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class DropInfo(proto.Message): - r"""Details of the final state "drop" and associated resource. - - Attributes: - cause (google.cloud.network_management_v1.types.DropInfo.Cause): - Cause that the packet is dropped. - resource_uri (str): - URI of the resource that caused the drop. - source_ip (str): - Source IP address of the dropped packet (if - relevant). - destination_ip (str): - Destination IP address of the dropped packet - (if relevant). - region (str): - Region of the dropped packet (if relevant). - """ - class Cause(proto.Enum): - r"""Drop cause types: - - Values: - CAUSE_UNSPECIFIED (0): - Cause is unspecified. - UNKNOWN_EXTERNAL_ADDRESS (1): - Destination external address cannot be - resolved to a known target. If the address is - used in a Google Cloud project, provide the - project ID as test input. - FOREIGN_IP_DISALLOWED (2): - A Compute Engine instance can only send or receive a packet - with a foreign IP address if ip_forward is enabled. - FIREWALL_RULE (3): - Dropped due to a firewall rule, unless - allowed due to connection tracking. - NO_ROUTE (4): - Dropped due to no matching routes. - ROUTE_BLACKHOLE (5): - Dropped due to invalid route. Route's next - hop is a blackhole. - ROUTE_WRONG_NETWORK (6): - Packet is sent to a wrong (unintended) - network. Example: you trace a packet from - VM1:Network1 to VM2:Network2, however, the route - configured in Network1 sends the packet destined - for VM2's IP address to Network3. - ROUTE_NEXT_HOP_IP_ADDRESS_NOT_RESOLVED (42): - Route's next hop IP address cannot be - resolved to a GCP resource. - ROUTE_NEXT_HOP_RESOURCE_NOT_FOUND (43): - Route's next hop resource is not found. - ROUTE_NEXT_HOP_INSTANCE_WRONG_NETWORK (49): - Route's next hop instance doesn't have a NIC - in the route's network. - ROUTE_NEXT_HOP_INSTANCE_NON_PRIMARY_IP (50): - Route's next hop IP address is not a primary - IP address of the next hop instance. - ROUTE_NEXT_HOP_FORWARDING_RULE_IP_MISMATCH (51): - Route's next hop forwarding rule doesn't - match next hop IP address. - ROUTE_NEXT_HOP_VPN_TUNNEL_NOT_ESTABLISHED (52): - Route's next hop VPN tunnel is down (does not - have valid IKE SAs). - ROUTE_NEXT_HOP_FORWARDING_RULE_TYPE_INVALID (53): - Route's next hop forwarding rule type is - invalid (it's not a forwarding rule of the - internal passthrough load balancer). - NO_ROUTE_FROM_INTERNET_TO_PRIVATE_IPV6_ADDRESS (44): - Packet is sent from the Internet to the - private IPv6 address. - VPN_TUNNEL_LOCAL_SELECTOR_MISMATCH (45): - The packet does not match a policy-based VPN - tunnel local selector. - VPN_TUNNEL_REMOTE_SELECTOR_MISMATCH (46): - The packet does not match a policy-based VPN - tunnel remote selector. - PRIVATE_TRAFFIC_TO_INTERNET (7): - Packet with internal destination address sent - to the internet gateway. - PRIVATE_GOOGLE_ACCESS_DISALLOWED (8): - Instance with only an internal IP address - tries to access Google API and services, but - private Google access is not enabled in the - subnet. - PRIVATE_GOOGLE_ACCESS_VIA_VPN_TUNNEL_UNSUPPORTED (47): - Source endpoint tries to access Google API - and services through the VPN tunnel to another - network, but Private Google Access needs to be - enabled in the source endpoint network. - NO_EXTERNAL_ADDRESS (9): - Instance with only an internal IP address - tries to access external hosts, but Cloud NAT is - not enabled in the subnet, unless special - configurations on a VM allow this connection. - UNKNOWN_INTERNAL_ADDRESS (10): - Destination internal address cannot be - resolved to a known target. If this is a shared - VPC scenario, verify if the service project ID - is provided as test input. Otherwise, verify if - the IP address is being used in the project. - FORWARDING_RULE_MISMATCH (11): - Forwarding rule's protocol and ports do not - match the packet header. - FORWARDING_RULE_NO_INSTANCES (12): - Forwarding rule does not have backends - configured. - FIREWALL_BLOCKING_LOAD_BALANCER_BACKEND_HEALTH_CHECK (13): - Firewalls block the health check probes to the backends and - cause the backends to be unavailable for traffic from the - load balancer. For more details, see `Health check firewall - rules `__. - INSTANCE_NOT_RUNNING (14): - Packet is sent from or to a Compute Engine - instance that is not in a running state. - GKE_CLUSTER_NOT_RUNNING (27): - Packet sent from or to a GKE cluster that is - not in running state. - CLOUD_SQL_INSTANCE_NOT_RUNNING (28): - Packet sent from or to a Cloud SQL instance - that is not in running state. - REDIS_INSTANCE_NOT_RUNNING (68): - Packet sent from or to a Redis Instance that - is not in running state. - REDIS_CLUSTER_NOT_RUNNING (69): - Packet sent from or to a Redis Cluster that - is not in running state. - TRAFFIC_TYPE_BLOCKED (15): - The type of traffic is blocked and the user cannot configure - a firewall rule to enable it. See `Always blocked - traffic `__ - for more details. - GKE_MASTER_UNAUTHORIZED_ACCESS (16): - Access to Google Kubernetes Engine cluster master's endpoint - is not authorized. See `Access to the cluster - endpoints `__ - for more details. - CLOUD_SQL_INSTANCE_UNAUTHORIZED_ACCESS (17): - Access to the Cloud SQL instance endpoint is not authorized. - See `Authorizing with authorized - networks `__ - for more details. - DROPPED_INSIDE_GKE_SERVICE (18): - Packet was dropped inside Google Kubernetes - Engine Service. - DROPPED_INSIDE_CLOUD_SQL_SERVICE (19): - Packet was dropped inside Cloud SQL Service. - GOOGLE_MANAGED_SERVICE_NO_PEERING (20): - Packet was dropped because there is no - peering between the originating network and the - Google Managed Services Network. - GOOGLE_MANAGED_SERVICE_NO_PSC_ENDPOINT (38): - Packet was dropped because the Google-managed - service uses Private Service Connect (PSC), but - the PSC endpoint is not found in the project. - GKE_PSC_ENDPOINT_MISSING (36): - Packet was dropped because the GKE cluster - uses Private Service Connect (PSC), but the PSC - endpoint is not found in the project. - CLOUD_SQL_INSTANCE_NO_IP_ADDRESS (21): - Packet was dropped because the Cloud SQL - instance has neither a private nor a public IP - address. - GKE_CONTROL_PLANE_REGION_MISMATCH (30): - Packet was dropped because a GKE cluster - private endpoint is unreachable from a region - different from the cluster's region. - PUBLIC_GKE_CONTROL_PLANE_TO_PRIVATE_DESTINATION (31): - Packet sent from a public GKE cluster control - plane to a private IP address. - GKE_CONTROL_PLANE_NO_ROUTE (32): - Packet was dropped because there is no route - from a GKE cluster control plane to a - destination network. - CLOUD_SQL_INSTANCE_NOT_CONFIGURED_FOR_EXTERNAL_TRAFFIC (33): - Packet sent from a Cloud SQL instance to an - external IP address is not allowed. The Cloud - SQL instance is not configured to send packets - to external IP addresses. - PUBLIC_CLOUD_SQL_INSTANCE_TO_PRIVATE_DESTINATION (34): - Packet sent from a Cloud SQL instance with - only a public IP address to a private IP - address. - CLOUD_SQL_INSTANCE_NO_ROUTE (35): - Packet was dropped because there is no route - from a Cloud SQL instance to a destination - network. - CLOUD_SQL_CONNECTOR_REQUIRED (63): - Packet was dropped because the Cloud SQL - instance requires all connections to use Cloud - SQL connectors and to target the Cloud SQL proxy - port (3307). - CLOUD_FUNCTION_NOT_ACTIVE (22): - Packet could be dropped because the Cloud - Function is not in an active status. - VPC_CONNECTOR_NOT_SET (23): - Packet could be dropped because no VPC - connector is set. - VPC_CONNECTOR_NOT_RUNNING (24): - Packet could be dropped because the VPC - connector is not in a running state. - VPC_CONNECTOR_SERVERLESS_TRAFFIC_BLOCKED (60): - Packet could be dropped because the traffic - from the serverless service to the VPC connector - is not allowed. - VPC_CONNECTOR_HEALTH_CHECK_TRAFFIC_BLOCKED (61): - Packet could be dropped because the health - check traffic to the VPC connector is not - allowed. - FORWARDING_RULE_REGION_MISMATCH (25): - Packet could be dropped because it was sent - from a different region to a regional forwarding - without global access. - PSC_CONNECTION_NOT_ACCEPTED (26): - The Private Service Connect endpoint is in a - project that is not approved to connect to the - service. - PSC_ENDPOINT_ACCESSED_FROM_PEERED_NETWORK (41): - The packet is sent to the Private Service Connect endpoint - over the peering, but `it's not - supported `__. - PSC_NEG_PRODUCER_ENDPOINT_NO_GLOBAL_ACCESS (48): - The packet is sent to the Private Service - Connect backend (network endpoint group), but - the producer PSC forwarding rule does not have - global access enabled. - PSC_NEG_PRODUCER_FORWARDING_RULE_MULTIPLE_PORTS (54): - The packet is sent to the Private Service - Connect backend (network endpoint group), but - the producer PSC forwarding rule has multiple - ports specified. - CLOUD_SQL_PSC_NEG_UNSUPPORTED (58): - The packet is sent to the Private Service - Connect backend (network endpoint group) - targeting a Cloud SQL service attachment, but - this configuration is not supported. - NO_NAT_SUBNETS_FOR_PSC_SERVICE_ATTACHMENT (57): - No NAT subnets are defined for the PSC - service attachment. - PSC_TRANSITIVITY_NOT_PROPAGATED (64): - PSC endpoint is accessed via NCC, but PSC - transitivity configuration is not yet - propagated. - HYBRID_NEG_NON_DYNAMIC_ROUTE_MATCHED (55): - The packet sent from the hybrid NEG proxy - matches a non-dynamic route, but such a - configuration is not supported. - HYBRID_NEG_NON_LOCAL_DYNAMIC_ROUTE_MATCHED (56): - The packet sent from the hybrid NEG proxy - matches a dynamic route with a next hop in a - different region, but such a configuration is - not supported. - CLOUD_RUN_REVISION_NOT_READY (29): - Packet sent from a Cloud Run revision that is - not ready. - DROPPED_INSIDE_PSC_SERVICE_PRODUCER (37): - Packet was dropped inside Private Service - Connect service producer. - LOAD_BALANCER_HAS_NO_PROXY_SUBNET (39): - Packet sent to a load balancer, which - requires a proxy-only subnet and the subnet is - not found. - CLOUD_NAT_NO_ADDRESSES (40): - Packet sent to Cloud Nat without active NAT - IPs. - ROUTING_LOOP (59): - Packet is stuck in a routing loop. - DROPPED_INSIDE_GOOGLE_MANAGED_SERVICE (62): - Packet is dropped inside a Google-managed - service due to being delivered in return trace - to an endpoint that doesn't match the endpoint - the packet was sent from in forward trace. Used - only for return traces. - LOAD_BALANCER_BACKEND_INVALID_NETWORK (65): - Packet is dropped due to a load balancer - backend instance not having a network interface - in the network expected by the load balancer. - BACKEND_SERVICE_NAMED_PORT_NOT_DEFINED (66): - Packet is dropped due to a backend service - named port not being defined on the instance - group level. - DESTINATION_IS_PRIVATE_NAT_IP_RANGE (67): - Packet is dropped due to a destination IP - range being part of a Private NAT IP range. - DROPPED_INSIDE_REDIS_INSTANCE_SERVICE (70): - Generic drop cause for a packet being dropped - inside a Redis Instance service project. - REDIS_INSTANCE_UNSUPPORTED_PORT (71): - Packet is dropped due to an unsupported port - being used to connect to a Redis Instance. Port - 6379 should be used to connect to a Redis - Instance. - REDIS_INSTANCE_CONNECTING_FROM_PUPI_ADDRESS (72): - Packet is dropped due to connecting from PUPI - address to a PSA based Redis Instance. - REDIS_INSTANCE_NO_ROUTE_TO_DESTINATION_NETWORK (73): - Packet is dropped due to no route to the - destination network. - REDIS_INSTANCE_NO_EXTERNAL_IP (74): - Redis Instance does not have an external IP - address. - REDIS_INSTANCE_UNSUPPORTED_PROTOCOL (78): - Packet is dropped due to an unsupported - protocol being used to connect to a Redis - Instance. Only TCP connections are accepted by a - Redis Instance. - DROPPED_INSIDE_REDIS_CLUSTER_SERVICE (75): - Generic drop cause for a packet being dropped - inside a Redis Cluster service project. - REDIS_CLUSTER_UNSUPPORTED_PORT (76): - Packet is dropped due to an unsupported port - being used to connect to a Redis Cluster. Ports - 6379 and 11000 to 13047 should be used to - connect to a Redis Cluster. - REDIS_CLUSTER_NO_EXTERNAL_IP (77): - Redis Cluster does not have an external IP - address. - REDIS_CLUSTER_UNSUPPORTED_PROTOCOL (79): - Packet is dropped due to an unsupported - protocol being used to connect to a Redis - Cluster. Only TCP connections are accepted by a - Redis Cluster. - NO_ADVERTISED_ROUTE_TO_GCP_DESTINATION (80): - Packet from the non-GCP (on-prem) or unknown - GCP network is dropped due to the destination IP - address not belonging to any IP prefix - advertised via BGP by the Cloud Router. - NO_TRAFFIC_SELECTOR_TO_GCP_DESTINATION (81): - Packet from the non-GCP (on-prem) or unknown - GCP network is dropped due to the destination IP - address not belonging to any IP prefix included - to the local traffic selector of the VPN tunnel. - NO_KNOWN_ROUTE_FROM_PEERED_NETWORK_TO_DESTINATION (82): - Packet from the unknown peered network is - dropped due to no known route from the source - network to the destination IP address. - PRIVATE_NAT_TO_PSC_ENDPOINT_UNSUPPORTED (83): - Sending packets processed by the Private NAT - Gateways to the Private Service Connect - endpoints is not supported. - """ - CAUSE_UNSPECIFIED = 0 - UNKNOWN_EXTERNAL_ADDRESS = 1 - FOREIGN_IP_DISALLOWED = 2 - FIREWALL_RULE = 3 - NO_ROUTE = 4 - ROUTE_BLACKHOLE = 5 - ROUTE_WRONG_NETWORK = 6 - ROUTE_NEXT_HOP_IP_ADDRESS_NOT_RESOLVED = 42 - ROUTE_NEXT_HOP_RESOURCE_NOT_FOUND = 43 - ROUTE_NEXT_HOP_INSTANCE_WRONG_NETWORK = 49 - ROUTE_NEXT_HOP_INSTANCE_NON_PRIMARY_IP = 50 - ROUTE_NEXT_HOP_FORWARDING_RULE_IP_MISMATCH = 51 - ROUTE_NEXT_HOP_VPN_TUNNEL_NOT_ESTABLISHED = 52 - ROUTE_NEXT_HOP_FORWARDING_RULE_TYPE_INVALID = 53 - NO_ROUTE_FROM_INTERNET_TO_PRIVATE_IPV6_ADDRESS = 44 - VPN_TUNNEL_LOCAL_SELECTOR_MISMATCH = 45 - VPN_TUNNEL_REMOTE_SELECTOR_MISMATCH = 46 - PRIVATE_TRAFFIC_TO_INTERNET = 7 - PRIVATE_GOOGLE_ACCESS_DISALLOWED = 8 - PRIVATE_GOOGLE_ACCESS_VIA_VPN_TUNNEL_UNSUPPORTED = 47 - NO_EXTERNAL_ADDRESS = 9 - UNKNOWN_INTERNAL_ADDRESS = 10 - FORWARDING_RULE_MISMATCH = 11 - FORWARDING_RULE_NO_INSTANCES = 12 - FIREWALL_BLOCKING_LOAD_BALANCER_BACKEND_HEALTH_CHECK = 13 - INSTANCE_NOT_RUNNING = 14 - GKE_CLUSTER_NOT_RUNNING = 27 - CLOUD_SQL_INSTANCE_NOT_RUNNING = 28 - REDIS_INSTANCE_NOT_RUNNING = 68 - REDIS_CLUSTER_NOT_RUNNING = 69 - TRAFFIC_TYPE_BLOCKED = 15 - GKE_MASTER_UNAUTHORIZED_ACCESS = 16 - CLOUD_SQL_INSTANCE_UNAUTHORIZED_ACCESS = 17 - DROPPED_INSIDE_GKE_SERVICE = 18 - DROPPED_INSIDE_CLOUD_SQL_SERVICE = 19 - GOOGLE_MANAGED_SERVICE_NO_PEERING = 20 - GOOGLE_MANAGED_SERVICE_NO_PSC_ENDPOINT = 38 - GKE_PSC_ENDPOINT_MISSING = 36 - CLOUD_SQL_INSTANCE_NO_IP_ADDRESS = 21 - GKE_CONTROL_PLANE_REGION_MISMATCH = 30 - PUBLIC_GKE_CONTROL_PLANE_TO_PRIVATE_DESTINATION = 31 - GKE_CONTROL_PLANE_NO_ROUTE = 32 - CLOUD_SQL_INSTANCE_NOT_CONFIGURED_FOR_EXTERNAL_TRAFFIC = 33 - PUBLIC_CLOUD_SQL_INSTANCE_TO_PRIVATE_DESTINATION = 34 - CLOUD_SQL_INSTANCE_NO_ROUTE = 35 - CLOUD_SQL_CONNECTOR_REQUIRED = 63 - CLOUD_FUNCTION_NOT_ACTIVE = 22 - VPC_CONNECTOR_NOT_SET = 23 - VPC_CONNECTOR_NOT_RUNNING = 24 - VPC_CONNECTOR_SERVERLESS_TRAFFIC_BLOCKED = 60 - VPC_CONNECTOR_HEALTH_CHECK_TRAFFIC_BLOCKED = 61 - FORWARDING_RULE_REGION_MISMATCH = 25 - PSC_CONNECTION_NOT_ACCEPTED = 26 - PSC_ENDPOINT_ACCESSED_FROM_PEERED_NETWORK = 41 - PSC_NEG_PRODUCER_ENDPOINT_NO_GLOBAL_ACCESS = 48 - PSC_NEG_PRODUCER_FORWARDING_RULE_MULTIPLE_PORTS = 54 - CLOUD_SQL_PSC_NEG_UNSUPPORTED = 58 - NO_NAT_SUBNETS_FOR_PSC_SERVICE_ATTACHMENT = 57 - PSC_TRANSITIVITY_NOT_PROPAGATED = 64 - HYBRID_NEG_NON_DYNAMIC_ROUTE_MATCHED = 55 - HYBRID_NEG_NON_LOCAL_DYNAMIC_ROUTE_MATCHED = 56 - CLOUD_RUN_REVISION_NOT_READY = 29 - DROPPED_INSIDE_PSC_SERVICE_PRODUCER = 37 - LOAD_BALANCER_HAS_NO_PROXY_SUBNET = 39 - CLOUD_NAT_NO_ADDRESSES = 40 - ROUTING_LOOP = 59 - DROPPED_INSIDE_GOOGLE_MANAGED_SERVICE = 62 - LOAD_BALANCER_BACKEND_INVALID_NETWORK = 65 - BACKEND_SERVICE_NAMED_PORT_NOT_DEFINED = 66 - DESTINATION_IS_PRIVATE_NAT_IP_RANGE = 67 - DROPPED_INSIDE_REDIS_INSTANCE_SERVICE = 70 - REDIS_INSTANCE_UNSUPPORTED_PORT = 71 - REDIS_INSTANCE_CONNECTING_FROM_PUPI_ADDRESS = 72 - REDIS_INSTANCE_NO_ROUTE_TO_DESTINATION_NETWORK = 73 - REDIS_INSTANCE_NO_EXTERNAL_IP = 74 - REDIS_INSTANCE_UNSUPPORTED_PROTOCOL = 78 - DROPPED_INSIDE_REDIS_CLUSTER_SERVICE = 75 - REDIS_CLUSTER_UNSUPPORTED_PORT = 76 - REDIS_CLUSTER_NO_EXTERNAL_IP = 77 - REDIS_CLUSTER_UNSUPPORTED_PROTOCOL = 79 - NO_ADVERTISED_ROUTE_TO_GCP_DESTINATION = 80 - NO_TRAFFIC_SELECTOR_TO_GCP_DESTINATION = 81 - NO_KNOWN_ROUTE_FROM_PEERED_NETWORK_TO_DESTINATION = 82 - PRIVATE_NAT_TO_PSC_ENDPOINT_UNSUPPORTED = 83 - - cause: Cause = proto.Field( - proto.ENUM, - number=1, - enum=Cause, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=2, - ) - source_ip: str = proto.Field( - proto.STRING, - number=3, - ) - destination_ip: str = proto.Field( - proto.STRING, - number=4, - ) - region: str = proto.Field( - proto.STRING, - number=5, - ) - - -class GKEMasterInfo(proto.Message): - r"""For display only. Metadata associated with a Google - Kubernetes Engine (GKE) cluster master. - - Attributes: - cluster_uri (str): - URI of a GKE cluster. - cluster_network_uri (str): - URI of a GKE cluster network. - internal_ip (str): - Internal IP address of a GKE cluster control - plane. - external_ip (str): - External IP address of a GKE cluster control - plane. - dns_endpoint (str): - DNS endpoint of a GKE cluster control plane. - """ - - cluster_uri: str = proto.Field( - proto.STRING, - number=2, - ) - cluster_network_uri: str = proto.Field( - proto.STRING, - number=4, - ) - internal_ip: str = proto.Field( - proto.STRING, - number=5, - ) - external_ip: str = proto.Field( - proto.STRING, - number=6, - ) - dns_endpoint: str = proto.Field( - proto.STRING, - number=7, - ) - - -class CloudSQLInstanceInfo(proto.Message): - r"""For display only. Metadata associated with a Cloud SQL - instance. - - Attributes: - display_name (str): - Name of a Cloud SQL instance. - uri (str): - URI of a Cloud SQL instance. - network_uri (str): - URI of a Cloud SQL instance network or empty - string if the instance does not have one. - internal_ip (str): - Internal IP address of a Cloud SQL instance. - external_ip (str): - External IP address of a Cloud SQL instance. - region (str): - Region in which the Cloud SQL instance is - running. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - network_uri: str = proto.Field( - proto.STRING, - number=4, - ) - internal_ip: str = proto.Field( - proto.STRING, - number=5, - ) - external_ip: str = proto.Field( - proto.STRING, - number=6, - ) - region: str = proto.Field( - proto.STRING, - number=7, - ) - - -class RedisInstanceInfo(proto.Message): - r"""For display only. Metadata associated with a Cloud Redis - Instance. - - Attributes: - display_name (str): - Name of a Cloud Redis Instance. - uri (str): - URI of a Cloud Redis Instance. - network_uri (str): - URI of a Cloud Redis Instance network. - primary_endpoint_ip (str): - Primary endpoint IP address of a Cloud Redis - Instance. - read_endpoint_ip (str): - Read endpoint IP address of a Cloud Redis - Instance (if applicable). - region (str): - Region in which the Cloud Redis Instance is - defined. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - network_uri: str = proto.Field( - proto.STRING, - number=3, - ) - primary_endpoint_ip: str = proto.Field( - proto.STRING, - number=4, - ) - read_endpoint_ip: str = proto.Field( - proto.STRING, - number=5, - ) - region: str = proto.Field( - proto.STRING, - number=6, - ) - - -class RedisClusterInfo(proto.Message): - r"""For display only. Metadata associated with a Redis Cluster. - - Attributes: - display_name (str): - Name of a Redis Cluster. - uri (str): - URI of a Redis Cluster in format - "projects/{project_id}/locations/{location}/clusters/{cluster_id}". - network_uri (str): - URI of a Redis Cluster network in format - "projects/{project_id}/global/networks/{network_id}". - discovery_endpoint_ip_address (str): - Discovery endpoint IP address of a Redis - Cluster. - secondary_endpoint_ip_address (str): - Secondary endpoint IP address of a Redis - Cluster. - location (str): - Name of the region in which the Redis Cluster - is defined. For example, "us-central1". - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - network_uri: str = proto.Field( - proto.STRING, - number=3, - ) - discovery_endpoint_ip_address: str = proto.Field( - proto.STRING, - number=4, - ) - secondary_endpoint_ip_address: str = proto.Field( - proto.STRING, - number=5, - ) - location: str = proto.Field( - proto.STRING, - number=6, - ) - - -class CloudFunctionInfo(proto.Message): - r"""For display only. Metadata associated with a Cloud Function. - - Attributes: - display_name (str): - Name of a Cloud Function. - uri (str): - URI of a Cloud Function. - location (str): - Location in which the Cloud Function is - deployed. - version_id (int): - Latest successfully deployed version id of - the Cloud Function. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - location: str = proto.Field( - proto.STRING, - number=3, - ) - version_id: int = proto.Field( - proto.INT64, - number=4, - ) - - -class CloudRunRevisionInfo(proto.Message): - r"""For display only. Metadata associated with a Cloud Run - revision. - - Attributes: - display_name (str): - Name of a Cloud Run revision. - uri (str): - URI of a Cloud Run revision. - location (str): - Location in which this revision is deployed. - service_uri (str): - URI of Cloud Run service this revision - belongs to. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - location: str = proto.Field( - proto.STRING, - number=4, - ) - service_uri: str = proto.Field( - proto.STRING, - number=5, - ) - - -class AppEngineVersionInfo(proto.Message): - r"""For display only. Metadata associated with an App Engine - version. - - Attributes: - display_name (str): - Name of an App Engine version. - uri (str): - URI of an App Engine version. - runtime (str): - Runtime of the App Engine version. - environment (str): - App Engine execution environment for a - version. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - runtime: str = proto.Field( - proto.STRING, - number=3, - ) - environment: str = proto.Field( - proto.STRING, - number=4, - ) - - -class VpcConnectorInfo(proto.Message): - r"""For display only. Metadata associated with a VPC connector. - - Attributes: - display_name (str): - Name of a VPC connector. - uri (str): - URI of a VPC connector. - location (str): - Location in which the VPC connector is - deployed. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - location: str = proto.Field( - proto.STRING, - number=3, - ) - - -class NatInfo(proto.Message): - r"""For display only. Metadata associated with NAT. - - Attributes: - type_ (google.cloud.network_management_v1.types.NatInfo.Type): - Type of NAT. - protocol (str): - IP protocol in string format, for example: - "TCP", "UDP", "ICMP". - network_uri (str): - URI of the network where NAT translation - takes place. - old_source_ip (str): - Source IP address before NAT translation. - new_source_ip (str): - Source IP address after NAT translation. - old_destination_ip (str): - Destination IP address before NAT - translation. - new_destination_ip (str): - Destination IP address after NAT translation. - old_source_port (int): - Source port before NAT translation. Only - valid when protocol is TCP or UDP. - new_source_port (int): - Source port after NAT translation. Only valid - when protocol is TCP or UDP. - old_destination_port (int): - Destination port before NAT translation. Only - valid when protocol is TCP or UDP. - new_destination_port (int): - Destination port after NAT translation. Only - valid when protocol is TCP or UDP. - router_uri (str): - Uri of the Cloud Router. Only valid when type is CLOUD_NAT. - nat_gateway_name (str): - The name of Cloud NAT Gateway. Only valid when type is - CLOUD_NAT. - """ - class Type(proto.Enum): - r"""Types of NAT. - - Values: - TYPE_UNSPECIFIED (0): - Type is unspecified. - INTERNAL_TO_EXTERNAL (1): - From Compute Engine instance's internal - address to external address. - EXTERNAL_TO_INTERNAL (2): - From Compute Engine instance's external - address to internal address. - CLOUD_NAT (3): - Cloud NAT Gateway. - PRIVATE_SERVICE_CONNECT (4): - Private service connect NAT. - """ - TYPE_UNSPECIFIED = 0 - INTERNAL_TO_EXTERNAL = 1 - EXTERNAL_TO_INTERNAL = 2 - CLOUD_NAT = 3 - PRIVATE_SERVICE_CONNECT = 4 - - type_: Type = proto.Field( - proto.ENUM, - number=1, - enum=Type, - ) - protocol: str = proto.Field( - proto.STRING, - number=2, - ) - network_uri: str = proto.Field( - proto.STRING, - number=3, - ) - old_source_ip: str = proto.Field( - proto.STRING, - number=4, - ) - new_source_ip: str = proto.Field( - proto.STRING, - number=5, - ) - old_destination_ip: str = proto.Field( - proto.STRING, - number=6, - ) - new_destination_ip: str = proto.Field( - proto.STRING, - number=7, - ) - old_source_port: int = proto.Field( - proto.INT32, - number=8, - ) - new_source_port: int = proto.Field( - proto.INT32, - number=9, - ) - old_destination_port: int = proto.Field( - proto.INT32, - number=10, - ) - new_destination_port: int = proto.Field( - proto.INT32, - number=11, - ) - router_uri: str = proto.Field( - proto.STRING, - number=12, - ) - nat_gateway_name: str = proto.Field( - proto.STRING, - number=13, - ) - - -class ProxyConnectionInfo(proto.Message): - r"""For display only. Metadata associated with ProxyConnection. - - Attributes: - protocol (str): - IP protocol in string format, for example: - "TCP", "UDP", "ICMP". - old_source_ip (str): - Source IP address of an original connection. - new_source_ip (str): - Source IP address of a new connection. - old_destination_ip (str): - Destination IP address of an original - connection - new_destination_ip (str): - Destination IP address of a new connection. - old_source_port (int): - Source port of an original connection. Only - valid when protocol is TCP or UDP. - new_source_port (int): - Source port of a new connection. Only valid - when protocol is TCP or UDP. - old_destination_port (int): - Destination port of an original connection. - Only valid when protocol is TCP or UDP. - new_destination_port (int): - Destination port of a new connection. Only - valid when protocol is TCP or UDP. - subnet_uri (str): - Uri of proxy subnet. - network_uri (str): - URI of the network where connection is - proxied. - """ - - protocol: str = proto.Field( - proto.STRING, - number=1, - ) - old_source_ip: str = proto.Field( - proto.STRING, - number=2, - ) - new_source_ip: str = proto.Field( - proto.STRING, - number=3, - ) - old_destination_ip: str = proto.Field( - proto.STRING, - number=4, - ) - new_destination_ip: str = proto.Field( - proto.STRING, - number=5, - ) - old_source_port: int = proto.Field( - proto.INT32, - number=6, - ) - new_source_port: int = proto.Field( - proto.INT32, - number=7, - ) - old_destination_port: int = proto.Field( - proto.INT32, - number=8, - ) - new_destination_port: int = proto.Field( - proto.INT32, - number=9, - ) - subnet_uri: str = proto.Field( - proto.STRING, - number=10, - ) - network_uri: str = proto.Field( - proto.STRING, - number=11, - ) - - -class LoadBalancerBackendInfo(proto.Message): - r"""For display only. Metadata associated with the load balancer - backend. - - Attributes: - name (str): - Display name of the backend. For example, it - might be an instance name for the instance group - backends, or an IP address and port for zonal - network endpoint group backends. - instance_uri (str): - URI of the backend instance (if applicable). - Populated for instance group backends, and zonal - NEG backends. - backend_service_uri (str): - URI of the backend service this backend - belongs to (if applicable). - instance_group_uri (str): - URI of the instance group this backend - belongs to (if applicable). - network_endpoint_group_uri (str): - URI of the network endpoint group this - backend belongs to (if applicable). - backend_bucket_uri (str): - URI of the backend bucket this backend - targets (if applicable). - psc_service_attachment_uri (str): - URI of the PSC service attachment this PSC - NEG backend targets (if applicable). - psc_google_api_target (str): - PSC Google API target this PSC NEG backend - targets (if applicable). - health_check_uri (str): - URI of the health check attached to this - backend (if applicable). - health_check_firewalls_config_state (google.cloud.network_management_v1.types.LoadBalancerBackendInfo.HealthCheckFirewallsConfigState): - Output only. Health check firewalls - configuration state for the backend. This is a - result of the static firewall analysis - (verifying that health check traffic from - required IP ranges to the backend is allowed or - not). The backend might still be unhealthy even - if these firewalls are configured. Please refer - to the documentation for more information: - - https://cloud.google.com/load-balancing/docs/firewall-rules - """ - class HealthCheckFirewallsConfigState(proto.Enum): - r"""Health check firewalls configuration state enum. - - Values: - HEALTH_CHECK_FIREWALLS_CONFIG_STATE_UNSPECIFIED (0): - Configuration state unspecified. It usually - means that the backend has no health check - attached, or there was an unexpected - configuration error preventing Connectivity - tests from verifying health check configuration. - FIREWALLS_CONFIGURED (1): - Firewall rules (policies) allowing health - check traffic from all required IP ranges to the - backend are configured. - FIREWALLS_PARTIALLY_CONFIGURED (2): - Firewall rules (policies) allow health check - traffic only from a part of required IP ranges. - FIREWALLS_NOT_CONFIGURED (3): - Firewall rules (policies) deny health check - traffic from all required IP ranges to the - backend. - FIREWALLS_UNSUPPORTED (4): - The network contains firewall rules of - unsupported types, so Connectivity tests were - not able to verify health check configuration - status. Please refer to the documentation for - the list of unsupported configurations: - - https://cloud.google.com/network-intelligence-center/docs/connectivity-tests/concepts/overview#unsupported-configs - """ - HEALTH_CHECK_FIREWALLS_CONFIG_STATE_UNSPECIFIED = 0 - FIREWALLS_CONFIGURED = 1 - FIREWALLS_PARTIALLY_CONFIGURED = 2 - FIREWALLS_NOT_CONFIGURED = 3 - FIREWALLS_UNSUPPORTED = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - instance_uri: str = proto.Field( - proto.STRING, - number=2, - ) - backend_service_uri: str = proto.Field( - proto.STRING, - number=3, - ) - instance_group_uri: str = proto.Field( - proto.STRING, - number=4, - ) - network_endpoint_group_uri: str = proto.Field( - proto.STRING, - number=5, - ) - backend_bucket_uri: str = proto.Field( - proto.STRING, - number=8, - ) - psc_service_attachment_uri: str = proto.Field( - proto.STRING, - number=9, - ) - psc_google_api_target: str = proto.Field( - proto.STRING, - number=10, - ) - health_check_uri: str = proto.Field( - proto.STRING, - number=6, - ) - health_check_firewalls_config_state: HealthCheckFirewallsConfigState = proto.Field( - proto.ENUM, - number=7, - enum=HealthCheckFirewallsConfigState, - ) - - -class StorageBucketInfo(proto.Message): - r"""For display only. Metadata associated with Storage Bucket. - - Attributes: - bucket (str): - Cloud Storage Bucket name. - """ - - bucket: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ServerlessNegInfo(proto.Message): - r"""For display only. Metadata associated with the serverless - network endpoint group backend. - - Attributes: - neg_uri (str): - URI of the serverless network endpoint group. - """ - - neg_uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-management/v1/mypy.ini b/owl-bot-staging/google-cloud-network-management/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-management/v1/noxfile.py b/owl-bot-staging/google-cloud-network-management/v1/noxfile.py deleted file mode 100644 index e09f07364b34..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-network-management' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/network_management_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/network_management_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-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py deleted file mode 100644 index c74b86142f00..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_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 CreateConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_create_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.CreateConnectivityTestRequest( - parent="parent_value", - test_id="test_id_value", - ) - - # Make the request - operation = client.create_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py deleted file mode 100644 index c27c11cc246a..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_create_connectivity_test_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 CreateConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_create_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.CreateConnectivityTestRequest( - parent="parent_value", - test_id="test_id_value", - ) - - # Make the request - operation = client.create_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py deleted file mode 100644 index cc7d4daf1552..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_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 DeleteConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_delete_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.DeleteConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py deleted file mode 100644 index 00d6602a4aef..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_delete_connectivity_test_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 DeleteConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_delete_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.DeleteConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py deleted file mode 100644 index 85b70752cf16..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_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 GetConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_get_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.GetConnectivityTestRequest( - name="name_value", - ) - - # Make the request - response = await client.get_connectivity_test(request=request) - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py deleted file mode 100644 index 40673d28a839..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_get_connectivity_test_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 GetConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_get_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.GetConnectivityTestRequest( - name="name_value", - ) - - # Make the request - response = client.get_connectivity_test(request=request) - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py deleted file mode 100644 index 15d2f1f0232f..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_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 ListConnectivityTests -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_list_connectivity_tests(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.ListConnectivityTestsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_connectivity_tests(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py deleted file mode 100644 index c595e917f169..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_list_connectivity_tests_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 ListConnectivityTests -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_list_connectivity_tests(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.ListConnectivityTestsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_connectivity_tests(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py deleted file mode 100644 index 9ba7e4c6759f..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_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 RerunConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_rerun_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.RerunConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.rerun_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py deleted file mode 100644 index c726b18eda73..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_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 RerunConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_rerun_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.RerunConnectivityTestRequest( - name="name_value", - ) - - # Make the request - operation = client.rerun_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py deleted file mode 100644 index a89f65bf0aa0..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_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 UpdateConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -async def sample_update_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceAsyncClient() - - # Initialize request argument(s) - request = network_management_v1.UpdateConnectivityTestRequest( - ) - - # Make the request - operation = client.update_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_async] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py deleted file mode 100644 index 503f72cf246b..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/networkmanagement_v1_generated_reachability_service_update_connectivity_test_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 UpdateConnectivityTest -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-management - - -# [START networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_management_v1 - - -def sample_update_connectivity_test(): - # Create a client - client = network_management_v1.ReachabilityServiceClient() - - # Initialize request argument(s) - request = network_management_v1.UpdateConnectivityTestRequest( - ) - - # Make the request - operation = client.update_connectivity_test(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_sync] diff --git a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json b/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json deleted file mode 100644 index a6a39ec02f7f..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json +++ /dev/null @@ -1,997 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.networkmanagement.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-network-management", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.create_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.CreateConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "CreateConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.CreateConnectivityTestRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "test_id", - "type": "str" - }, - { - "name": "resource", - "type": "google.cloud.network_management_v1.types.ConnectivityTest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for CreateConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.create_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.CreateConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "CreateConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.CreateConnectivityTestRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "test_id", - "type": "str" - }, - { - "name": "resource", - "type": "google.cloud.network_management_v1.types.ConnectivityTest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for CreateConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_CreateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_create_connectivity_test_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.delete_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.DeleteConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "DeleteConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.DeleteConnectivityTestRequest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for DeleteConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.delete_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.DeleteConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "DeleteConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.DeleteConnectivityTestRequest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for DeleteConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_DeleteConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_delete_connectivity_test_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.get_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.GetConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "GetConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.GetConnectivityTestRequest" - }, - { - "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.network_management_v1.types.ConnectivityTest", - "shortName": "get_connectivity_test" - }, - "description": "Sample for GetConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.get_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.GetConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "GetConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.GetConnectivityTestRequest" - }, - { - "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.network_management_v1.types.ConnectivityTest", - "shortName": "get_connectivity_test" - }, - "description": "Sample for GetConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_GetConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_get_connectivity_test_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.list_connectivity_tests", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.ListConnectivityTests", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "ListConnectivityTests" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.ListConnectivityTestsRequest" - }, - { - "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.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsAsyncPager", - "shortName": "list_connectivity_tests" - }, - "description": "Sample for ListConnectivityTests", - "file": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_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": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.list_connectivity_tests", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.ListConnectivityTests", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "ListConnectivityTests" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.ListConnectivityTestsRequest" - }, - { - "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.network_management_v1.services.reachability_service.pagers.ListConnectivityTestsPager", - "shortName": "list_connectivity_tests" - }, - "description": "Sample for ListConnectivityTests", - "file": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_ListConnectivityTests_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": "networkmanagement_v1_generated_reachability_service_list_connectivity_tests_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.rerun_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.RerunConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "RerunConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.RerunConnectivityTestRequest" - }, - { - "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": "rerun_connectivity_test" - }, - "description": "Sample for RerunConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.rerun_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.RerunConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "RerunConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.RerunConnectivityTestRequest" - }, - { - "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": "rerun_connectivity_test" - }, - "description": "Sample for RerunConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_RerunConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_rerun_connectivity_test_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient", - "shortName": "ReachabilityServiceAsyncClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceAsyncClient.update_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.UpdateConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "UpdateConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.UpdateConnectivityTestRequest" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "resource", - "type": "google.cloud.network_management_v1.types.ConnectivityTest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for UpdateConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient", - "shortName": "ReachabilityServiceClient" - }, - "fullName": "google.cloud.network_management_v1.ReachabilityServiceClient.update_connectivity_test", - "method": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService.UpdateConnectivityTest", - "service": { - "fullName": "google.cloud.networkmanagement.v1.ReachabilityService", - "shortName": "ReachabilityService" - }, - "shortName": "UpdateConnectivityTest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_management_v1.types.UpdateConnectivityTestRequest" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "resource", - "type": "google.cloud.network_management_v1.types.ConnectivityTest" - }, - { - "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_connectivity_test" - }, - "description": "Sample for UpdateConnectivityTest", - "file": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkmanagement_v1_generated_ReachabilityService_UpdateConnectivityTest_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": "networkmanagement_v1_generated_reachability_service_update_connectivity_test_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py b/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py deleted file mode 100644 index 33791cd81e72..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/scripts/fixup_network_management_v1_keywords.py +++ /dev/null @@ -1,181 +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 network_managementCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_connectivity_test': ('parent', 'test_id', 'resource', ), - 'delete_connectivity_test': ('name', ), - 'get_connectivity_test': ('name', ), - 'list_connectivity_tests': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'rerun_connectivity_test': ('name', ), - 'update_connectivity_test': ('update_mask', 'resource', ), - } - - 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=network_managementCallTransformer(), -): - """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 network_management 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-network-management/v1/setup.py b/owl-bot-staging/google-cloud-network-management/v1/setup.py deleted file mode 100644 index 110a46599b9a..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-network-management' - - -description = "Google Cloud Network Management API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/network_management/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-management" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_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-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py b/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py deleted file mode 100644 index b5d474b02375..000000000000 --- a/owl-bot-staging/google-cloud-network-management/v1/tests/unit/gapic/network_management_v1/test_reachability_service.py +++ /dev/null @@ -1,7469 +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.location import locations_pb2 -from google.cloud.network_management_v1.services.reachability_service import ReachabilityServiceAsyncClient -from google.cloud.network_management_v1.services.reachability_service import ReachabilityServiceClient -from google.cloud.network_management_v1.services.reachability_service import pagers -from google.cloud.network_management_v1.services.reachability_service import transports -from google.cloud.network_management_v1.types import connectivity_test -from google.cloud.network_management_v1.types import reachability -from google.cloud.network_management_v1.types import trace -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import 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 ReachabilityServiceClient._get_default_mtls_endpoint(None) is None - assert ReachabilityServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ReachabilityServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ReachabilityServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ReachabilityServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ReachabilityServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ReachabilityServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ReachabilityServiceClient._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 ReachabilityServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ReachabilityServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ReachabilityServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ReachabilityServiceClient._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 ReachabilityServiceClient._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 ReachabilityServiceClient._get_client_cert_source(None, False) is None - assert ReachabilityServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ReachabilityServiceClient._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 ReachabilityServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ReachabilityServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) -@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ReachabilityServiceClient._DEFAULT_UNIVERSE - default_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ReachabilityServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ReachabilityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT - assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "always") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT - assert ReachabilityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ReachabilityServiceClient.DEFAULT_MTLS_ENDPOINT - assert ReachabilityServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ReachabilityServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ReachabilityServiceClient._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 ReachabilityServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ReachabilityServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ReachabilityServiceClient._get_universe_domain(None, None) == ReachabilityServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ReachabilityServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ReachabilityServiceClient, "grpc"), - (ReachabilityServiceAsyncClient, "grpc_asyncio"), - (ReachabilityServiceClient, "rest"), -]) -def test_reachability_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'networkmanagement.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networkmanagement.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ReachabilityServiceGrpcTransport, "grpc"), - (transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ReachabilityServiceRestTransport, "rest"), -]) -def test_reachability_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ReachabilityServiceClient, "grpc"), - (ReachabilityServiceAsyncClient, "grpc_asyncio"), - (ReachabilityServiceClient, "rest"), -]) -def test_reachability_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'networkmanagement.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networkmanagement.googleapis.com' - ) - - -def test_reachability_service_client_get_transport_class(): - transport = ReachabilityServiceClient.get_transport_class() - available_transports = [ - transports.ReachabilityServiceGrpcTransport, - transports.ReachabilityServiceRestTransport, - ] - assert transport in available_transports - - transport = ReachabilityServiceClient.get_transport_class("grpc") - assert transport == transports.ReachabilityServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc"), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest"), -]) -@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) -@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) -def test_reachability_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(ReachabilityServiceClient, '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(ReachabilityServiceClient, '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", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", "true"), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", "false"), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", "true"), - (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) -@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_reachability_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ReachabilityServiceClient, ReachabilityServiceAsyncClient -]) -@mock.patch.object(ReachabilityServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReachabilityServiceClient)) -@mock.patch.object(ReachabilityServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReachabilityServiceAsyncClient)) -def test_reachability_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_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", [ - ReachabilityServiceClient, ReachabilityServiceAsyncClient -]) -@mock.patch.object(ReachabilityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceClient)) -@mock.patch.object(ReachabilityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReachabilityServiceAsyncClient)) -def test_reachability_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ReachabilityServiceClient._DEFAULT_UNIVERSE - default_endpoint = ReachabilityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ReachabilityServiceClient._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", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc"), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest"), -]) -def test_reachability_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", grpc_helpers), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ReachabilityServiceClient, transports.ReachabilityServiceRestTransport, "rest", None), -]) -def test_reachability_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_reachability_service_client_client_options_from_dict(): - with mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ReachabilityServiceClient( - 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", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport, "grpc", grpc_helpers), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_reachability_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "networkmanagement.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="networkmanagement.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - reachability.ListConnectivityTestsRequest, - dict, -]) -def test_list_connectivity_tests(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_connectivity_tests), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = reachability.ListConnectivityTestsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.ListConnectivityTestsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConnectivityTestsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_connectivity_tests_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 = ReachabilityServiceClient( - 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 = reachability.ListConnectivityTestsRequest( - 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_connectivity_tests), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_connectivity_tests(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.ListConnectivityTestsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_connectivity_tests_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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_connectivity_tests in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_tests] = mock_rpc - request = {} - client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_connectivity_tests(request) - - # Establish that a new wrapper 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_connectivity_tests_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 = ReachabilityServiceAsyncClient( - 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_connectivity_tests 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_connectivity_tests] = mock_rpc - - request = {} - await client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_connectivity_tests(request) - - # Establish that a new wrapper 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_connectivity_tests_async(transport: str = 'grpc_asyncio', request_type=reachability.ListConnectivityTestsRequest): - client = ReachabilityServiceAsyncClient( - 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_connectivity_tests), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.ListConnectivityTestsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConnectivityTestsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_connectivity_tests_async_from_dict(): - await test_list_connectivity_tests_async(request_type=dict) - -def test_list_connectivity_tests_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.ListConnectivityTestsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - call.return_value = reachability.ListConnectivityTestsResponse() - client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_connectivity_tests_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.ListConnectivityTestsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse()) - await client.list_connectivity_tests(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_connectivity_tests_flattened(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = reachability.ListConnectivityTestsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_connectivity_tests( - 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_connectivity_tests_flattened_error(): - client = ReachabilityServiceClient( - 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_connectivity_tests( - reachability.ListConnectivityTestsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_connectivity_tests_flattened_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = reachability.ListConnectivityTestsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_connectivity_tests( - 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_connectivity_tests_flattened_error_async(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_tests( - reachability.ListConnectivityTestsRequest(), - parent='parent_value', - ) - - -def test_list_connectivity_tests_pager(transport_name: str = "grpc"): - client = ReachabilityServiceClient( - 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_connectivity_tests), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - next_page_token='abc', - ), - reachability.ListConnectivityTestsResponse( - resources=[], - next_page_token='def', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - ], - next_page_token='ghi', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_connectivity_tests(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, connectivity_test.ConnectivityTest) - for i in results) -def test_list_connectivity_tests_pages(transport_name: str = "grpc"): - client = ReachabilityServiceClient( - 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_connectivity_tests), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - next_page_token='abc', - ), - reachability.ListConnectivityTestsResponse( - resources=[], - next_page_token='def', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - ], - next_page_token='ghi', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - ), - RuntimeError, - ) - pages = list(client.list_connectivity_tests(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_connectivity_tests_async_pager(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - next_page_token='abc', - ), - reachability.ListConnectivityTestsResponse( - resources=[], - next_page_token='def', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - ], - next_page_token='ghi', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_connectivity_tests(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, connectivity_test.ConnectivityTest) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_connectivity_tests_async_pages(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - next_page_token='abc', - ), - reachability.ListConnectivityTestsResponse( - resources=[], - next_page_token='def', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - ], - next_page_token='ghi', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - ), - 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_connectivity_tests(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", [ - reachability.GetConnectivityTestRequest, - dict, -]) -def test_get_connectivity_test(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = connectivity_test.ConnectivityTest( - name='name_value', - description='description_value', - protocol='protocol_value', - related_projects=['related_projects_value'], - display_name='display_name_value', - round_trip=True, - bypass_firewall_checks=True, - ) - response = client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.GetConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, connectivity_test.ConnectivityTest) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.protocol == 'protocol_value' - assert response.related_projects == ['related_projects_value'] - assert response.display_name == 'display_name_value' - assert response.round_trip is True - assert response.bypass_firewall_checks is True - - -def test_get_connectivity_test_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 = ReachabilityServiceClient( - 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 = reachability.GetConnectivityTestRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_connectivity_test(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.GetConnectivityTestRequest( - name='name_value', - ) - -def test_get_connectivity_test_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - request = {} - client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( - 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_connectivity_test 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_connectivity_test] = mock_rpc - - request = {} - await client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.GetConnectivityTestRequest): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest( - name='name_value', - description='description_value', - protocol='protocol_value', - related_projects=['related_projects_value'], - display_name='display_name_value', - round_trip=True, - bypass_firewall_checks=True, - )) - response = await client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.GetConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, connectivity_test.ConnectivityTest) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.protocol == 'protocol_value' - assert response.related_projects == ['related_projects_value'] - assert response.display_name == 'display_name_value' - assert response.round_trip is True - assert response.bypass_firewall_checks is True - - -@pytest.mark.asyncio -async def test_get_connectivity_test_async_from_dict(): - await test_get_connectivity_test_async(request_type=dict) - -def test_get_connectivity_test_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.GetConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - call.return_value = connectivity_test.ConnectivityTest() - client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_connectivity_test_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.GetConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest()) - await client.get_connectivity_test(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_connectivity_test_flattened(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = connectivity_test.ConnectivityTest() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_connectivity_test( - 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_connectivity_test_flattened_error(): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.GetConnectivityTestRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_connectivity_test_flattened_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = connectivity_test.ConnectivityTest() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_connectivity_test( - 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_connectivity_test_flattened_error_async(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test( - reachability.GetConnectivityTestRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - reachability.CreateConnectivityTestRequest, - dict, -]) -def test_create_connectivity_test(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.CreateConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_connectivity_test_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 = ReachabilityServiceClient( - 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 = reachability.CreateConnectivityTestRequest( - parent='parent_value', - test_id='test_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_connectivity_test(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.CreateConnectivityTestRequest( - parent='parent_value', - test_id='test_id_value', - ) - -def test_create_connectivity_test_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - request = {} - client.create_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( - 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_connectivity_test 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_connectivity_test] = mock_rpc - - request = {} - await client.create_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.CreateConnectivityTestRequest): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test), - '__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_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.CreateConnectivityTestRequest() - 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_connectivity_test_async_from_dict(): - await test_create_connectivity_test_async(request_type=dict) - -def test_create_connectivity_test_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.CreateConnectivityTestRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_connectivity_test_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.CreateConnectivityTestRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_connectivity_test(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_connectivity_test_flattened(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__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_connectivity_test( - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].test_id - mock_val = 'test_id_value' - assert arg == mock_val - arg = args[0].resource - mock_val = connectivity_test.ConnectivityTest(name='name_value') - assert arg == mock_val - - -def test_create_connectivity_test_flattened_error(): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.CreateConnectivityTestRequest(), - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_connectivity_test_flattened_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__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_connectivity_test( - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].test_id - mock_val = 'test_id_value' - assert arg == mock_val - arg = args[0].resource - mock_val = connectivity_test.ConnectivityTest(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_connectivity_test_flattened_error_async(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test( - reachability.CreateConnectivityTestRequest(), - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - reachability.UpdateConnectivityTestRequest, - dict, -]) -def test_update_connectivity_test(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.UpdateConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_connectivity_test_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 = ReachabilityServiceClient( - 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 = reachability.UpdateConnectivityTestRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_connectivity_test(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.UpdateConnectivityTestRequest( - ) - -def test_update_connectivity_test_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - request = {} - client.update_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( - 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_connectivity_test 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_connectivity_test] = mock_rpc - - request = {} - await client.update_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.UpdateConnectivityTestRequest): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test), - '__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_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.UpdateConnectivityTestRequest() - 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_connectivity_test_async_from_dict(): - await test_update_connectivity_test_async(request_type=dict) - -def test_update_connectivity_test_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.UpdateConnectivityTestRequest() - - request.resource.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_connectivity_test_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.UpdateConnectivityTestRequest() - - request.resource.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource.name=name_value', - ) in kw['metadata'] - - -def test_update_connectivity_test_flattened(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__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_connectivity_test( - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(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].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - arg = args[0].resource - mock_val = connectivity_test.ConnectivityTest(name='name_value') - assert arg == mock_val - - -def test_update_connectivity_test_flattened_error(): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.UpdateConnectivityTestRequest(), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_connectivity_test_flattened_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__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_connectivity_test( - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(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].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - arg = args[0].resource - mock_val = connectivity_test.ConnectivityTest(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_connectivity_test_flattened_error_async(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test( - reachability.UpdateConnectivityTestRequest(), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - reachability.RerunConnectivityTestRequest, - dict, -]) -def test_rerun_connectivity_test(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rerun_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.RerunConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rerun_connectivity_test_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 = ReachabilityServiceClient( - 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 = reachability.RerunConnectivityTestRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.rerun_connectivity_test(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.RerunConnectivityTestRequest( - name='name_value', - ) - -def test_rerun_connectivity_test_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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.rerun_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.rerun_connectivity_test] = mock_rpc - request = {} - client.rerun_connectivity_test(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.rerun_connectivity_test(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_rerun_connectivity_test_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 = ReachabilityServiceAsyncClient( - 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.rerun_connectivity_test 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.rerun_connectivity_test] = mock_rpc - - request = {} - await client.rerun_connectivity_test(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.rerun_connectivity_test(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_rerun_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.RerunConnectivityTestRequest): - client = ReachabilityServiceAsyncClient( - 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.rerun_connectivity_test), - '__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.rerun_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.RerunConnectivityTestRequest() - 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_rerun_connectivity_test_async_from_dict(): - await test_rerun_connectivity_test_async(request_type=dict) - -def test_rerun_connectivity_test_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.RerunConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rerun_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_rerun_connectivity_test_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.RerunConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rerun_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - reachability.DeleteConnectivityTestRequest, - dict, -]) -def test_delete_connectivity_test(request_type, transport: str = 'grpc'): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reachability.DeleteConnectivityTestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_connectivity_test_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 = ReachabilityServiceClient( - 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 = reachability.DeleteConnectivityTestRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_connectivity_test(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reachability.DeleteConnectivityTestRequest( - name='name_value', - ) - -def test_delete_connectivity_test_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - request = {} - client.delete_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_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 = ReachabilityServiceAsyncClient( - 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_connectivity_test 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_connectivity_test] = mock_rpc - - request = {} - await client.delete_connectivity_test(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_connectivity_test(request) - - # Establish that a new wrapper 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_connectivity_test_async(transport: str = 'grpc_asyncio', request_type=reachability.DeleteConnectivityTestRequest): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test), - '__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_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reachability.DeleteConnectivityTestRequest() - 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_connectivity_test_async_from_dict(): - await test_delete_connectivity_test_async(request_type=dict) - -def test_delete_connectivity_test_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.DeleteConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_connectivity_test_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reachability.DeleteConnectivityTestRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_connectivity_test(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_connectivity_test_flattened(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__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_connectivity_test( - 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_connectivity_test_flattened_error(): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.DeleteConnectivityTestRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_connectivity_test_flattened_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__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_connectivity_test( - 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_connectivity_test_flattened_error_async(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test( - reachability.DeleteConnectivityTestRequest(), - name='name_value', - ) - - -def test_list_connectivity_tests_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 = ReachabilityServiceClient( - 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_connectivity_tests in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_tests] = mock_rpc - - request = {} - client.list_connectivity_tests(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_connectivity_tests(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_connectivity_tests_rest_required_fields(request_type=reachability.ListConnectivityTestsRequest): - transport_class = transports.ReachabilityServiceRestTransport - - 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_connectivity_tests._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_connectivity_tests._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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = reachability.ListConnectivityTestsResponse() - # Mock the http request call 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_connectivity_tests_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_connectivity_tests._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_connectivity_tests_rest_flattened(): - client = ReachabilityServiceClient( - 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 = reachability.ListConnectivityTestsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/global'} - - # 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(**mock_args) - - # Establish that the underlying call 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/global}/connectivityTests" % client.transport._host, args[1]) - - -def test_list_connectivity_tests_rest_flattened_error(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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_connectivity_tests( - reachability.ListConnectivityTestsRequest(), - parent='parent_value', - ) - - -def test_list_connectivity_tests_rest_pager(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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 = ( - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - next_page_token='abc', - ), - reachability.ListConnectivityTestsResponse( - resources=[], - next_page_token='def', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - ], - next_page_token='ghi', - ), - reachability.ListConnectivityTestsResponse( - resources=[ - connectivity_test.ConnectivityTest(), - connectivity_test.ConnectivityTest(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(reachability.ListConnectivityTestsResponse.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/global'} - - pager = client.list_connectivity_tests(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, connectivity_test.ConnectivityTest) - for i in results) - - pages = list(client.list_connectivity_tests(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_connectivity_test_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 = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - - request = {} - client.get_connectivity_test(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.GetConnectivityTestRequest): - transport_class = transports.ReachabilityServiceRestTransport - - 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = connectivity_test.ConnectivityTest() - # Mock the http request call 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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_connectivity_test_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_connectivity_test._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_connectivity_test_rest_flattened(): - client = ReachabilityServiceClient( - 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 = connectivity_test.ConnectivityTest() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/global/connectivityTests/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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(**mock_args) - - # Establish that the underlying call 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/global/connectivityTests/*}" % client.transport._host, args[1]) - - -def test_get_connectivity_test_rest_flattened_error(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.GetConnectivityTestRequest(), - name='name_value', - ) - - -def test_create_connectivity_test_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 = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - - request = {} - client.create_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.CreateConnectivityTestRequest): - transport_class = transports.ReachabilityServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["test_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 "testId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_connectivity_test._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "testId" in jsonified_request - assert jsonified_request["testId"] == request_init["test_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["testId"] = 'test_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_connectivity_test._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("test_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 "testId" in jsonified_request - assert jsonified_request["testId"] == 'test_id_value' - - client = ReachabilityServiceClient( - 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_connectivity_test(request) - - expected_params = [ - ( - "testId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_connectivity_test_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_connectivity_test._get_unset_required_fields({}) - assert set(unset_fields) == (set(("testId", )) & set(("parent", "testId", "resource", ))) - - -def test_create_connectivity_test_rest_flattened(): - client = ReachabilityServiceClient( - 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/global'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(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.create_connectivity_test(**mock_args) - - # Establish that the underlying call 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/global}/connectivityTests" % client.transport._host, args[1]) - - -def test_create_connectivity_test_rest_flattened_error(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.CreateConnectivityTestRequest(), - parent='parent_value', - test_id='test_id_value', - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - -def test_update_connectivity_test_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 = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - - request = {} - client.update_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.UpdateConnectivityTestRequest): - transport_class = transports.ReachabilityServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_connectivity_test._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_connectivity_test._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_connectivity_test(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_connectivity_test_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_connectivity_test._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", "resource", ))) - - -def test_update_connectivity_test_rest_flattened(): - client = ReachabilityServiceClient( - 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 = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(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.update_connectivity_test(**mock_args) - - # Establish that the underlying call 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/{resource.name=projects/*/locations/global/connectivityTests/*}" % client.transport._host, args[1]) - - -def test_update_connectivity_test_rest_flattened_error(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.UpdateConnectivityTestRequest(), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - resource=connectivity_test.ConnectivityTest(name='name_value'), - ) - - -def test_rerun_connectivity_test_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 = ReachabilityServiceClient( - 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.rerun_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.rerun_connectivity_test] = mock_rpc - - request = {} - client.rerun_connectivity_test(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.rerun_connectivity_test(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_rerun_connectivity_test_rest_required_fields(request_type=reachability.RerunConnectivityTestRequest): - transport_class = transports.ReachabilityServiceRestTransport - - 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()).rerun_connectivity_test._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()).rerun_connectivity_test._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 = ReachabilityServiceClient( - 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.rerun_connectivity_test(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_rerun_connectivity_test_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.rerun_connectivity_test._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_connectivity_test_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 = ReachabilityServiceClient( - 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_connectivity_test in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_connectivity_test] = mock_rpc - - request = {} - client.delete_connectivity_test(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_connectivity_test(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_connectivity_test_rest_required_fields(request_type=reachability.DeleteConnectivityTestRequest): - transport_class = transports.ReachabilityServiceRestTransport - - 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( - 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_connectivity_test(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_connectivity_test_rest_unset_required_fields(): - transport = transports.ReachabilityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_connectivity_test._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_connectivity_test_rest_flattened(): - client = ReachabilityServiceClient( - 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/global/connectivityTests/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_connectivity_test(**mock_args) - - # Establish that the underlying call 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/global/connectivityTests/*}" % client.transport._host, args[1]) - - -def test_delete_connectivity_test_rest_flattened_error(transport: str = 'rest'): - client = ReachabilityServiceClient( - 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_connectivity_test( - reachability.DeleteConnectivityTestRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ReachabilityServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ReachabilityServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ReachabilityServiceGrpcTransport, - transports.ReachabilityServiceGrpcAsyncIOTransport, - transports.ReachabilityServiceRestTransport, -]) -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 = ReachabilityServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ReachabilityServiceClient( - 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_connectivity_tests_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - call.return_value = reachability.ListConnectivityTestsResponse() - client.list_connectivity_tests(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.ListConnectivityTestsRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - call.return_value = connectivity_test.ConnectivityTest() - client.get_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.GetConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.CreateConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.UpdateConnectivityTestRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_rerun_connectivity_test_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rerun_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.RerunConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_grpc(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.DeleteConnectivityTestRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ReachabilityServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_tests_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reachability.ListConnectivityTestsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_connectivity_tests(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.ListConnectivityTestsRequest() - - assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(connectivity_test.ConnectivityTest( - name='name_value', - description='description_value', - protocol='protocol_value', - related_projects=['related_projects_value'], - display_name='display_name_value', - round_trip=True, - bypass_firewall_checks=True, - )) - await client.get_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.GetConnectivityTestRequest() - - assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__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_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.CreateConnectivityTestRequest() - - assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__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_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.UpdateConnectivityTestRequest() - - assert args[0] == request_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_rerun_connectivity_test_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__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.rerun_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.RerunConnectivityTestRequest() - - assert args[0] == request_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_connectivity_test_empty_call_grpc_asyncio(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__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_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.DeleteConnectivityTestRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ReachabilityServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_connectivity_tests_rest_bad_request(request_type=reachability.ListConnectivityTestsRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/global'} - 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_connectivity_tests(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.ListConnectivityTestsRequest, - dict, -]) -def test_list_connectivity_tests_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/global'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = reachability.ListConnectivityTestsResponse( - 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 = reachability.ListConnectivityTestsResponse.pb(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_connectivity_tests(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConnectivityTestsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_connectivity_tests_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_list_connectivity_tests") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_list_connectivity_tests") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.ListConnectivityTestsRequest.pb(reachability.ListConnectivityTestsRequest()) - 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 = reachability.ListConnectivityTestsResponse.to_json(reachability.ListConnectivityTestsResponse()) - req.return_value.content = return_value - - request = reachability.ListConnectivityTestsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = reachability.ListConnectivityTestsResponse() - - client.list_connectivity_tests(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_connectivity_test_rest_bad_request(request_type=reachability.GetConnectivityTestRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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_connectivity_test(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.GetConnectivityTestRequest, - dict, -]) -def test_get_connectivity_test_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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 = connectivity_test.ConnectivityTest( - name='name_value', - description='description_value', - protocol='protocol_value', - related_projects=['related_projects_value'], - display_name='display_name_value', - round_trip=True, - bypass_firewall_checks=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 = connectivity_test.ConnectivityTest.pb(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_connectivity_test(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, connectivity_test.ConnectivityTest) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.protocol == 'protocol_value' - assert response.related_projects == ['related_projects_value'] - assert response.display_name == 'display_name_value' - assert response.round_trip is True - assert response.bypass_firewall_checks is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_connectivity_test_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_get_connectivity_test") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_get_connectivity_test") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.GetConnectivityTestRequest.pb(reachability.GetConnectivityTestRequest()) - 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 = connectivity_test.ConnectivityTest.to_json(connectivity_test.ConnectivityTest()) - req.return_value.content = return_value - - request = reachability.GetConnectivityTestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = connectivity_test.ConnectivityTest() - - client.get_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_connectivity_test_rest_bad_request(request_type=reachability.CreateConnectivityTestRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/global'} - 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_connectivity_test(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.CreateConnectivityTestRequest, - dict, -]) -def test_create_connectivity_test_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/global'} - request_init["resource"] = {'name': 'name_value', 'description': 'description_value', 'source': {'ip_address': 'ip_address_value', 'port': 453, 'instance': 'instance_value', 'forwarding_rule': 'forwarding_rule_value', 'forwarding_rule_target': 1, 'load_balancer_id': 'load_balancer_id_value', 'load_balancer_type': 1, 'gke_master_cluster': 'gke_master_cluster_value', 'fqdn': 'fqdn_value', 'cloud_sql_instance': 'cloud_sql_instance_value', 'redis_instance': 'redis_instance_value', 'redis_cluster': 'redis_cluster_value', 'cloud_function': {'uri': 'uri_value'}, 'app_engine_version': {'uri': 'uri_value'}, 'cloud_run_revision': {'uri': 'uri_value'}, 'network': 'network_value', 'network_type': 1, 'project_id': 'project_id_value'}, 'destination': {}, 'protocol': 'protocol_value', 'related_projects': ['related_projects_value1', 'related_projects_value2'], 'display_name': 'display_name_value', 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'reachability_details': {'result': 1, 'verify_time': {}, 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'traces': [{'endpoint_info': {'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'protocol': 'protocol_value', 'source_port': 1205, 'destination_port': 1734, 'source_network_uri': 'source_network_uri_value', 'destination_network_uri': 'destination_network_uri_value', 'source_agent_uri': 'source_agent_uri_value'}, 'steps': [{'description': 'description_value', 'state': 1, 'causes_drop': True, 'project_id': 'project_id_value', 'instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'interface': 'interface_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'network_tags': ['network_tags_value1', 'network_tags_value2'], 'service_account': 'service_account_value', 'psc_network_attachment_uri': 'psc_network_attachment_uri_value'}, 'firewall': {'display_name': 'display_name_value', 'uri': 'uri_value', 'direction': 'direction_value', 'action': 'action_value', 'priority': 898, 'network_uri': 'network_uri_value', 'target_tags': ['target_tags_value1', 'target_tags_value2'], 'target_service_accounts': ['target_service_accounts_value1', 'target_service_accounts_value2'], 'policy': 'policy_value', 'policy_uri': 'policy_uri_value', 'firewall_rule_type': 1}, 'route': {'route_type': 1, 'next_hop_type': 1, 'route_scope': 1, 'display_name': 'display_name_value', 'uri': 'uri_value', 'region': 'region_value', 'dest_ip_range': 'dest_ip_range_value', 'next_hop': 'next_hop_value', 'network_uri': 'network_uri_value', 'priority': 898, 'instance_tags': ['instance_tags_value1', 'instance_tags_value2'], 'src_ip_range': 'src_ip_range_value', 'dest_port_ranges': ['dest_port_ranges_value1', 'dest_port_ranges_value2'], 'src_port_ranges': ['src_port_ranges_value1', 'src_port_ranges_value2'], 'protocols': ['protocols_value1', 'protocols_value2'], 'ncc_hub_uri': 'ncc_hub_uri_value', 'ncc_spoke_uri': 'ncc_spoke_uri_value', 'advertised_route_source_router_uri': 'advertised_route_source_router_uri_value', 'advertised_route_next_hop_uri': 'advertised_route_next_hop_uri_value'}, 'endpoint': {}, 'google_service': {'source_ip': 'source_ip_value', 'google_service_type': 1}, 'forwarding_rule': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_protocol': 'matched_protocol_value', 'matched_port_range': 'matched_port_range_value', 'vip': 'vip_value', 'target': 'target_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'load_balancer_name': 'load_balancer_name_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'vpn_gateway': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'ip_address': 'ip_address_value', 'vpn_tunnel_uri': 'vpn_tunnel_uri_value', 'region': 'region_value'}, 'vpn_tunnel': {'display_name': 'display_name_value', 'uri': 'uri_value', 'source_gateway': 'source_gateway_value', 'remote_gateway': 'remote_gateway_value', 'remote_gateway_ip': 'remote_gateway_ip_value', 'source_gateway_ip': 'source_gateway_ip_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'routing_type': 1}, 'vpc_connector': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value'}, 'deliver': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'storage_bucket': 'storage_bucket_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'forward': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value'}, 'abort': {'cause': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'projects_missing_permission': ['projects_missing_permission_value1', 'projects_missing_permission_value2']}, 'drop': {'cause': 1, 'resource_uri': 'resource_uri_value', 'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'region': 'region_value'}, 'load_balancer': {'load_balancer_type': 1, 'health_check_uri': 'health_check_uri_value', 'backends': [{'display_name': 'display_name_value', 'uri': 'uri_value', 'health_check_firewall_state': 1, 'health_check_allowing_firewall_rules': ['health_check_allowing_firewall_rules_value1', 'health_check_allowing_firewall_rules_value2'], 'health_check_blocking_firewall_rules': ['health_check_blocking_firewall_rules_value1', 'health_check_blocking_firewall_rules_value2']}], 'backend_type': 1, 'backend_uri': 'backend_uri_value'}, 'network': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_subnet_uri': 'matched_subnet_uri_value', 'matched_ip_range': 'matched_ip_range_value', 'region': 'region_value'}, 'gke_master': {'cluster_uri': 'cluster_uri_value', 'cluster_network_uri': 'cluster_network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'dns_endpoint': 'dns_endpoint_value'}, 'cloud_sql_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'region': 'region_value'}, 'redis_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'primary_endpoint_ip': 'primary_endpoint_ip_value', 'read_endpoint_ip': 'read_endpoint_ip_value', 'region': 'region_value'}, 'redis_cluster': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'discovery_endpoint_ip_address': 'discovery_endpoint_ip_address_value', 'secondary_endpoint_ip_address': 'secondary_endpoint_ip_address_value', 'location': 'location_value'}, 'cloud_function': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'version_id': 1074}, 'app_engine_version': {'display_name': 'display_name_value', 'uri': 'uri_value', 'runtime': 'runtime_value', 'environment': 'environment_value'}, 'cloud_run_revision': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'service_uri': 'service_uri_value'}, 'nat': {'type_': 1, 'protocol': 'protocol_value', 'network_uri': 'network_uri_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'router_uri': 'router_uri_value', 'nat_gateway_name': 'nat_gateway_name_value'}, 'proxy_connection': {'protocol': 'protocol_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'subnet_uri': 'subnet_uri_value', 'network_uri': 'network_uri_value'}, 'load_balancer_backend_info': {'name': 'name_value', 'instance_uri': 'instance_uri_value', 'backend_service_uri': 'backend_service_uri_value', 'instance_group_uri': 'instance_group_uri_value', 'network_endpoint_group_uri': 'network_endpoint_group_uri_value', 'backend_bucket_uri': 'backend_bucket_uri_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value', 'health_check_uri': 'health_check_uri_value', 'health_check_firewalls_config_state': 1}, 'storage_bucket': {'bucket': 'bucket_value'}, 'serverless_neg': {'neg_uri': 'neg_uri_value'}}], 'forward_trace_id': 1679}]}, 'probing_details': {'result': 1, 'verify_time': {}, 'error': {}, 'abort_cause': 1, 'sent_probe_count': 1721, 'successful_probe_count': 2367, 'endpoint_info': {}, 'probing_latency': {'latency_percentiles': [{'percent': 753, 'latency_micros': 1500}]}, 'destination_egress_location': {'metropolitan_area': 'metropolitan_area_value'}}, 'round_trip': True, 'return_reachability_details': {}, 'bypass_firewall_checks': True} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = reachability.CreateConnectivityTestRequest.meta.fields["resource"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["resource"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["resource"][field])): - del request_init["resource"][field][i][subfield] - else: - del request_init["resource"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_create_connectivity_test") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_create_connectivity_test") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.CreateConnectivityTestRequest.pb(reachability.CreateConnectivityTestRequest()) - 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 = reachability.CreateConnectivityTestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_connectivity_test_rest_bad_request(request_type=reachability.UpdateConnectivityTestRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/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.update_connectivity_test(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.UpdateConnectivityTestRequest, - dict, -]) -def test_update_connectivity_test_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'resource': {'name': 'projects/sample1/locations/global/connectivityTests/sample2'}} - request_init["resource"] = {'name': 'projects/sample1/locations/global/connectivityTests/sample2', 'description': 'description_value', 'source': {'ip_address': 'ip_address_value', 'port': 453, 'instance': 'instance_value', 'forwarding_rule': 'forwarding_rule_value', 'forwarding_rule_target': 1, 'load_balancer_id': 'load_balancer_id_value', 'load_balancer_type': 1, 'gke_master_cluster': 'gke_master_cluster_value', 'fqdn': 'fqdn_value', 'cloud_sql_instance': 'cloud_sql_instance_value', 'redis_instance': 'redis_instance_value', 'redis_cluster': 'redis_cluster_value', 'cloud_function': {'uri': 'uri_value'}, 'app_engine_version': {'uri': 'uri_value'}, 'cloud_run_revision': {'uri': 'uri_value'}, 'network': 'network_value', 'network_type': 1, 'project_id': 'project_id_value'}, 'destination': {}, 'protocol': 'protocol_value', 'related_projects': ['related_projects_value1', 'related_projects_value2'], 'display_name': 'display_name_value', 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'reachability_details': {'result': 1, 'verify_time': {}, 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'traces': [{'endpoint_info': {'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'protocol': 'protocol_value', 'source_port': 1205, 'destination_port': 1734, 'source_network_uri': 'source_network_uri_value', 'destination_network_uri': 'destination_network_uri_value', 'source_agent_uri': 'source_agent_uri_value'}, 'steps': [{'description': 'description_value', 'state': 1, 'causes_drop': True, 'project_id': 'project_id_value', 'instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'interface': 'interface_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'network_tags': ['network_tags_value1', 'network_tags_value2'], 'service_account': 'service_account_value', 'psc_network_attachment_uri': 'psc_network_attachment_uri_value'}, 'firewall': {'display_name': 'display_name_value', 'uri': 'uri_value', 'direction': 'direction_value', 'action': 'action_value', 'priority': 898, 'network_uri': 'network_uri_value', 'target_tags': ['target_tags_value1', 'target_tags_value2'], 'target_service_accounts': ['target_service_accounts_value1', 'target_service_accounts_value2'], 'policy': 'policy_value', 'policy_uri': 'policy_uri_value', 'firewall_rule_type': 1}, 'route': {'route_type': 1, 'next_hop_type': 1, 'route_scope': 1, 'display_name': 'display_name_value', 'uri': 'uri_value', 'region': 'region_value', 'dest_ip_range': 'dest_ip_range_value', 'next_hop': 'next_hop_value', 'network_uri': 'network_uri_value', 'priority': 898, 'instance_tags': ['instance_tags_value1', 'instance_tags_value2'], 'src_ip_range': 'src_ip_range_value', 'dest_port_ranges': ['dest_port_ranges_value1', 'dest_port_ranges_value2'], 'src_port_ranges': ['src_port_ranges_value1', 'src_port_ranges_value2'], 'protocols': ['protocols_value1', 'protocols_value2'], 'ncc_hub_uri': 'ncc_hub_uri_value', 'ncc_spoke_uri': 'ncc_spoke_uri_value', 'advertised_route_source_router_uri': 'advertised_route_source_router_uri_value', 'advertised_route_next_hop_uri': 'advertised_route_next_hop_uri_value'}, 'endpoint': {}, 'google_service': {'source_ip': 'source_ip_value', 'google_service_type': 1}, 'forwarding_rule': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_protocol': 'matched_protocol_value', 'matched_port_range': 'matched_port_range_value', 'vip': 'vip_value', 'target': 'target_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'load_balancer_name': 'load_balancer_name_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'vpn_gateway': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'ip_address': 'ip_address_value', 'vpn_tunnel_uri': 'vpn_tunnel_uri_value', 'region': 'region_value'}, 'vpn_tunnel': {'display_name': 'display_name_value', 'uri': 'uri_value', 'source_gateway': 'source_gateway_value', 'remote_gateway': 'remote_gateway_value', 'remote_gateway_ip': 'remote_gateway_ip_value', 'source_gateway_ip': 'source_gateway_ip_value', 'network_uri': 'network_uri_value', 'region': 'region_value', 'routing_type': 1}, 'vpc_connector': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value'}, 'deliver': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'storage_bucket': 'storage_bucket_value', 'psc_google_api_target': 'psc_google_api_target_value'}, 'forward': {'target': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value'}, 'abort': {'cause': 1, 'resource_uri': 'resource_uri_value', 'ip_address': 'ip_address_value', 'projects_missing_permission': ['projects_missing_permission_value1', 'projects_missing_permission_value2']}, 'drop': {'cause': 1, 'resource_uri': 'resource_uri_value', 'source_ip': 'source_ip_value', 'destination_ip': 'destination_ip_value', 'region': 'region_value'}, 'load_balancer': {'load_balancer_type': 1, 'health_check_uri': 'health_check_uri_value', 'backends': [{'display_name': 'display_name_value', 'uri': 'uri_value', 'health_check_firewall_state': 1, 'health_check_allowing_firewall_rules': ['health_check_allowing_firewall_rules_value1', 'health_check_allowing_firewall_rules_value2'], 'health_check_blocking_firewall_rules': ['health_check_blocking_firewall_rules_value1', 'health_check_blocking_firewall_rules_value2']}], 'backend_type': 1, 'backend_uri': 'backend_uri_value'}, 'network': {'display_name': 'display_name_value', 'uri': 'uri_value', 'matched_subnet_uri': 'matched_subnet_uri_value', 'matched_ip_range': 'matched_ip_range_value', 'region': 'region_value'}, 'gke_master': {'cluster_uri': 'cluster_uri_value', 'cluster_network_uri': 'cluster_network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'dns_endpoint': 'dns_endpoint_value'}, 'cloud_sql_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'internal_ip': 'internal_ip_value', 'external_ip': 'external_ip_value', 'region': 'region_value'}, 'redis_instance': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'primary_endpoint_ip': 'primary_endpoint_ip_value', 'read_endpoint_ip': 'read_endpoint_ip_value', 'region': 'region_value'}, 'redis_cluster': {'display_name': 'display_name_value', 'uri': 'uri_value', 'network_uri': 'network_uri_value', 'discovery_endpoint_ip_address': 'discovery_endpoint_ip_address_value', 'secondary_endpoint_ip_address': 'secondary_endpoint_ip_address_value', 'location': 'location_value'}, 'cloud_function': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'version_id': 1074}, 'app_engine_version': {'display_name': 'display_name_value', 'uri': 'uri_value', 'runtime': 'runtime_value', 'environment': 'environment_value'}, 'cloud_run_revision': {'display_name': 'display_name_value', 'uri': 'uri_value', 'location': 'location_value', 'service_uri': 'service_uri_value'}, 'nat': {'type_': 1, 'protocol': 'protocol_value', 'network_uri': 'network_uri_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'router_uri': 'router_uri_value', 'nat_gateway_name': 'nat_gateway_name_value'}, 'proxy_connection': {'protocol': 'protocol_value', 'old_source_ip': 'old_source_ip_value', 'new_source_ip': 'new_source_ip_value', 'old_destination_ip': 'old_destination_ip_value', 'new_destination_ip': 'new_destination_ip_value', 'old_source_port': 1619, 'new_source_port': 1630, 'old_destination_port': 2148, 'new_destination_port': 2159, 'subnet_uri': 'subnet_uri_value', 'network_uri': 'network_uri_value'}, 'load_balancer_backend_info': {'name': 'name_value', 'instance_uri': 'instance_uri_value', 'backend_service_uri': 'backend_service_uri_value', 'instance_group_uri': 'instance_group_uri_value', 'network_endpoint_group_uri': 'network_endpoint_group_uri_value', 'backend_bucket_uri': 'backend_bucket_uri_value', 'psc_service_attachment_uri': 'psc_service_attachment_uri_value', 'psc_google_api_target': 'psc_google_api_target_value', 'health_check_uri': 'health_check_uri_value', 'health_check_firewalls_config_state': 1}, 'storage_bucket': {'bucket': 'bucket_value'}, 'serverless_neg': {'neg_uri': 'neg_uri_value'}}], 'forward_trace_id': 1679}]}, 'probing_details': {'result': 1, 'verify_time': {}, 'error': {}, 'abort_cause': 1, 'sent_probe_count': 1721, 'successful_probe_count': 2367, 'endpoint_info': {}, 'probing_latency': {'latency_percentiles': [{'percent': 753, 'latency_micros': 1500}]}, 'destination_egress_location': {'metropolitan_area': 'metropolitan_area_value'}}, 'round_trip': True, 'return_reachability_details': {}, 'bypass_firewall_checks': True} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = reachability.UpdateConnectivityTestRequest.meta.fields["resource"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["resource"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["resource"][field])): - del request_init["resource"][field][i][subfield] - else: - del request_init["resource"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_update_connectivity_test") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_update_connectivity_test") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.UpdateConnectivityTestRequest.pb(reachability.UpdateConnectivityTestRequest()) - 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 = reachability.UpdateConnectivityTestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_rerun_connectivity_test_rest_bad_request(request_type=reachability.RerunConnectivityTestRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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.rerun_connectivity_test(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.RerunConnectivityTestRequest, - dict, -]) -def test_rerun_connectivity_test_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # 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.rerun_connectivity_test(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_rerun_connectivity_test_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_rerun_connectivity_test") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_rerun_connectivity_test") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.RerunConnectivityTestRequest.pb(reachability.RerunConnectivityTestRequest()) - 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 = reachability.RerunConnectivityTestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.rerun_connectivity_test(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_connectivity_test_rest_bad_request(request_type=reachability.DeleteConnectivityTestRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/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.delete_connectivity_test(request) - - -@pytest.mark.parametrize("request_type", [ - reachability.DeleteConnectivityTestRequest, - dict, -]) -def test_delete_connectivity_test_rest_call_success(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/global/connectivityTests/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # 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_connectivity_test(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_connectivity_test_rest_interceptors(null_interceptor): - transport = transports.ReachabilityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReachabilityServiceRestInterceptor(), - ) - client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_delete_connectivity_test") as post, \ - mock.patch.object(transports.ReachabilityServiceRestInterceptor, "pre_delete_connectivity_test") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reachability.DeleteConnectivityTestRequest.pb(reachability.DeleteConnectivityTestRequest()) - 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 = reachability.DeleteConnectivityTestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_connectivity_test(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 = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - 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_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/global/connectivityTests/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.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/global/connectivityTests/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 = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/global/operations/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_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/global/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/global'}, 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/global'} - 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 = ReachabilityServiceClient( - 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_connectivity_tests_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_connectivity_tests), - '__call__') as call: - client.list_connectivity_tests(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.ListConnectivityTestsRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_connectivity_test), - '__call__') as call: - client.get_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.GetConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_connectivity_test), - '__call__') as call: - client.create_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.CreateConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_connectivity_test), - '__call__') as call: - client.update_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.UpdateConnectivityTestRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_rerun_connectivity_test_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.rerun_connectivity_test), - '__call__') as call: - client.rerun_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.RerunConnectivityTestRequest() - - assert args[0] == request_msg - - -# This 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_connectivity_test_empty_call_rest(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_connectivity_test), - '__call__') as call: - client.delete_connectivity_test(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reachability.DeleteConnectivityTestRequest() - - assert args[0] == request_msg - - -def test_reachability_service_rest_lro_client(): - client = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ReachabilityServiceGrpcTransport, - ) - -def test_reachability_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ReachabilityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_reachability_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ReachabilityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_connectivity_tests', - 'get_connectivity_test', - 'create_connectivity_test', - 'update_connectivity_test', - 'rerun_connectivity_test', - 'delete_connectivity_test', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_reachability_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ReachabilityServiceTransport( - 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_reachability_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ReachabilityServiceTransport() - adc.assert_called_once() - - -def test_reachability_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ReachabilityServiceClient() - 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.ReachabilityServiceGrpcTransport, - transports.ReachabilityServiceGrpcAsyncIOTransport, - ], -) -def test_reachability_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ReachabilityServiceGrpcTransport, - transports.ReachabilityServiceGrpcAsyncIOTransport, - transports.ReachabilityServiceRestTransport, - ], -) -def test_reachability_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ReachabilityServiceGrpcTransport, grpc_helpers), - (transports.ReachabilityServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_reachability_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "networkmanagement.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="networkmanagement.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) -def test_reachability_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_reachability_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ReachabilityServiceRestTransport ( - 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_reachability_service_host_no_port(transport_name): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networkmanagement.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networkmanagement.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networkmanagement.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_reachability_service_host_with_port(transport_name): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networkmanagement.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networkmanagement.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networkmanagement.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_reachability_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ReachabilityServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ReachabilityServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_connectivity_tests._session - session2 = client2.transport.list_connectivity_tests._session - assert session1 != session2 - session1 = client1.transport.get_connectivity_test._session - session2 = client2.transport.get_connectivity_test._session - assert session1 != session2 - session1 = client1.transport.create_connectivity_test._session - session2 = client2.transport.create_connectivity_test._session - assert session1 != session2 - session1 = client1.transport.update_connectivity_test._session - session2 = client2.transport.update_connectivity_test._session - assert session1 != session2 - session1 = client1.transport.rerun_connectivity_test._session - session2 = client2.transport.rerun_connectivity_test._session - assert session1 != session2 - session1 = client1.transport.delete_connectivity_test._session - session2 = client2.transport.delete_connectivity_test._session - assert session1 != session2 -def test_reachability_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ReachabilityServiceGrpcTransport( - 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_reachability_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ReachabilityServiceGrpcAsyncIOTransport( - 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.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) -def test_reachability_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport]) -def test_reachability_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_reachability_service_grpc_lro_client(): - client = ReachabilityServiceClient( - 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_reachability_service_grpc_lro_async_client(): - client = ReachabilityServiceAsyncClient( - 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_connectivity_test_path(): - project = "squid" - test = "clam" - expected = "projects/{project}/locations/global/connectivityTests/{test}".format(project=project, test=test, ) - actual = ReachabilityServiceClient.connectivity_test_path(project, test) - assert expected == actual - - -def test_parse_connectivity_test_path(): - expected = { - "project": "whelk", - "test": "octopus", - } - path = ReachabilityServiceClient.connectivity_test_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.parse_connectivity_test_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ReachabilityServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = ReachabilityServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = ReachabilityServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = ReachabilityServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ReachabilityServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = ReachabilityServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = ReachabilityServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = ReachabilityServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ReachabilityServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = ReachabilityServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ReachabilityServiceClient.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.ReachabilityServiceTransport, '_prep_wrapped_messages') as prep: - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ReachabilityServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ReachabilityServiceClient.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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = ReachabilityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = ReachabilityServiceClient( - 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 = ReachabilityServiceAsyncClient( - 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 = ReachabilityServiceClient( - 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 = ReachabilityServiceClient( - 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", [ - (ReachabilityServiceClient, transports.ReachabilityServiceGrpcTransport), - (ReachabilityServiceAsyncClient, transports.ReachabilityServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py b/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py index 825d9da38825..dfa813a06996 100644 --- a/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py +++ b/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py @@ -132,6 +132,15 @@ class ConnectivityTest(proto.Message): creating a new test, updating an existing test, or triggering a one-time rerun of an existing test. + round_trip (bool): + Whether run analysis for the return path from + destination to source. Default value is false. + return_reachability_details (google.cloud.network_management_v1.types.ReachabilityDetails): + Output only. The reachability details of this + test from the latest run for the return path. + The details are updated when creating a new + test, updating an existing test, or triggering a + one-time rerun of an existing test. bypass_firewall_checks (bool): Whether the test should skip firewall checking. If not provided, we assume false. @@ -192,6 +201,15 @@ class ConnectivityTest(proto.Message): number=14, message="ProbingDetails", ) + round_trip: bool = proto.Field( + proto.BOOL, + number=15, + ) + return_reachability_details: "ReachabilityDetails" = proto.Field( + proto.MESSAGE, + number=16, + message="ReachabilityDetails", + ) bypass_firewall_checks: bool = proto.Field( proto.BOOL, number=17, diff --git a/packages/google-cloud-network-management/tests/unit/gapic/network_management_v1/test_reachability_service.py b/packages/google-cloud-network-management/tests/unit/gapic/network_management_v1/test_reachability_service.py index c9f0c06a74cd..df0e32dd94b3 100644 --- a/packages/google-cloud-network-management/tests/unit/gapic/network_management_v1/test_reachability_service.py +++ b/packages/google-cloud-network-management/tests/unit/gapic/network_management_v1/test_reachability_service.py @@ -1726,6 +1726,7 @@ def test_get_connectivity_test(request_type, transport: str = "grpc"): protocol="protocol_value", related_projects=["related_projects_value"], display_name="display_name_value", + round_trip=True, bypass_firewall_checks=True, ) response = client.get_connectivity_test(request) @@ -1743,6 +1744,7 @@ def test_get_connectivity_test(request_type, transport: str = "grpc"): assert response.protocol == "protocol_value" assert response.related_projects == ["related_projects_value"] assert response.display_name == "display_name_value" + assert response.round_trip is True assert response.bypass_firewall_checks is True @@ -1884,6 +1886,7 @@ async def test_get_connectivity_test_async( protocol="protocol_value", related_projects=["related_projects_value"], display_name="display_name_value", + round_trip=True, bypass_firewall_checks=True, ) ) @@ -1902,6 +1905,7 @@ async def test_get_connectivity_test_async( assert response.protocol == "protocol_value" assert response.related_projects == ["related_projects_value"] assert response.display_name == "display_name_value" + assert response.round_trip is True assert response.bypass_firewall_checks is True @@ -4855,6 +4859,7 @@ async def test_get_connectivity_test_empty_call_grpc_asyncio(): protocol="protocol_value", related_projects=["related_projects_value"], display_name="display_name_value", + round_trip=True, bypass_firewall_checks=True, ) ) @@ -5159,6 +5164,7 @@ def test_get_connectivity_test_rest_call_success(request_type): protocol="protocol_value", related_projects=["related_projects_value"], display_name="display_name_value", + round_trip=True, bypass_firewall_checks=True, ) @@ -5180,6 +5186,7 @@ def test_get_connectivity_test_rest_call_success(request_type): assert response.protocol == "protocol_value" assert response.related_projects == ["related_projects_value"] assert response.display_name == "display_name_value" + assert response.round_trip is True assert response.bypass_firewall_checks is True @@ -5613,6 +5620,8 @@ def test_create_connectivity_test_rest_call_success(request_type): "metropolitan_area": "metropolitan_area_value" }, }, + "round_trip": True, + "return_reachability_details": {}, "bypass_firewall_checks": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -6139,6 +6148,8 @@ def test_update_connectivity_test_rest_call_success(request_type): "metropolitan_area": "metropolitan_area_value" }, }, + "round_trip": True, + "return_reachability_details": {}, "bypass_firewall_checks": True, } # The version of a generated dependency at test runtime may differ from the version used during generation.