From 789553a7f4d1ebaddaddf5482945f9c9428d5715 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 6 Oct 2021 22:58:18 +0000 Subject: [PATCH 1/2] feat: add context manager support in client chore: fix docstring for first attribute of protos committer: @busunkim96 PiperOrigin-RevId: 401271153 Source-Link: https://github.com/googleapis/googleapis/commit/787f8c9a731f44e74a90b9847d48659ca9462d10 Source-Link: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 ++ owl-bot-staging/v1/docs/index.rst | 7 + .../servicedirectory_v1/lookup_service.rst | 6 + .../registration_service.rst | 10 + .../v1/docs/servicedirectory_v1/services.rst | 7 + .../v1/docs/servicedirectory_v1/types.rst | 7 + .../google/cloud/servicedirectory/__init__.py | 73 + .../v1/google/cloud/servicedirectory/py.typed | 2 + .../cloud/servicedirectory_v1/__init__.py | 74 + .../servicedirectory_v1/gapic_metadata.json | 227 + .../google/cloud/servicedirectory_v1/py.typed | 2 + .../servicedirectory_v1/services/__init__.py | 15 + .../services/lookup_service/__init__.py | 22 + .../services/lookup_service/async_client.py | 226 + .../services/lookup_service/client.py | 433 ++ .../lookup_service/transports/__init__.py | 33 + .../lookup_service/transports/base.py | 177 + .../lookup_service/transports/grpc.py | 256 + .../lookup_service/transports/grpc_asyncio.py | 261 + .../services/registration_service/__init__.py | 22 + .../registration_service/async_client.py | 1736 +++++ .../services/registration_service/client.py | 1948 ++++++ .../services/registration_service/pagers.py | 387 ++ .../transports/__init__.py | 33 + .../registration_service/transports/base.py | 424 ++ .../registration_service/transports/grpc.py | 724 +++ .../transports/grpc_asyncio.py | 729 +++ .../servicedirectory_v1/types/__init__.py | 74 + .../servicedirectory_v1/types/endpoint.py | 90 + .../types/lookup_service.py | 95 + .../servicedirectory_v1/types/namespace.py | 55 + .../types/registration_service.py | 614 ++ .../servicedirectory_v1/types/service.py | 87 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + .../fixup_servicedirectory_v1_keywords.py | 194 + owl-bot-staging/v1/setup.py | 54 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/servicedirectory_v1/__init__.py | 16 + .../test_lookup_service.py | 1157 ++++ .../test_registration_service.py | 5654 ++++++++++++++++ owl-bot-staging/v1beta1/.coveragerc | 17 + owl-bot-staging/v1beta1/MANIFEST.in | 2 + owl-bot-staging/v1beta1/README.rst | 49 + owl-bot-staging/v1beta1/docs/conf.py | 376 ++ owl-bot-staging/v1beta1/docs/index.rst | 7 + .../lookup_service.rst | 6 + .../registration_service.rst | 10 + .../servicedirectory_v1beta1/services.rst | 7 + .../docs/servicedirectory_v1beta1/types.rst | 7 + .../google/cloud/servicedirectory/__init__.py | 73 + .../google/cloud/servicedirectory/py.typed | 2 + .../servicedirectory_v1beta1/__init__.py | 74 + .../gapic_metadata.json | 227 + .../cloud/servicedirectory_v1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../services/lookup_service/__init__.py | 22 + .../services/lookup_service/async_client.py | 229 + .../services/lookup_service/client.py | 445 ++ .../lookup_service/transports/__init__.py | 33 + .../lookup_service/transports/base.py | 177 + .../lookup_service/transports/grpc.py | 257 + .../lookup_service/transports/grpc_asyncio.py | 262 + .../services/registration_service/__init__.py | 22 + .../registration_service/async_client.py | 1740 +++++ .../services/registration_service/client.py | 1961 ++++++ .../services/registration_service/pagers.py | 387 ++ .../transports/__init__.py | 33 + .../registration_service/transports/base.py | 424 ++ .../registration_service/transports/grpc.py | 725 +++ .../transports/grpc_asyncio.py | 730 +++ .../types/__init__.py | 74 + .../types/endpoint.py | 130 + .../types/lookup_service.py | 120 + .../types/namespace.py | 73 + .../types/registration_service.py | 675 ++ .../servicedirectory_v1beta1/types/service.py | 111 + owl-bot-staging/v1beta1/mypy.ini | 3 + owl-bot-staging/v1beta1/noxfile.py | 132 + ...fixup_servicedirectory_v1beta1_keywords.py | 194 + owl-bot-staging/v1beta1/setup.py | 54 + owl-bot-staging/v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../servicedirectory_v1beta1/__init__.py | 16 + .../test_lookup_service.py | 1176 ++++ .../test_registration_service.py | 5686 +++++++++++++++++ 92 files changed, 33371 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/docs/servicedirectory_v1/lookup_service.rst create mode 100644 owl-bot-staging/v1/docs/servicedirectory_v1/registration_service.rst create mode 100644 owl-bot-staging/v1/docs/servicedirectory_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/servicedirectory_v1/types.rst create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/endpoint.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/lookup_service.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/namespace.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/registration_service.py create mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/service.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/scripts/fixup_servicedirectory_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_registration_service.py create mode 100644 owl-bot-staging/v1beta1/.coveragerc create mode 100644 owl-bot-staging/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1beta1/README.rst create mode 100644 owl-bot-staging/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/lookup_service.rst create mode 100644 owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/registration_service.rst create mode 100644 owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/services.rst create mode 100644 owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/types.rst create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/endpoint.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/lookup_service.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/namespace.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/registration_service.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/service.py create mode 100644 owl-bot-staging/v1beta1/mypy.ini create mode 100644 owl-bot-staging/v1beta1/noxfile.py create mode 100644 owl-bot-staging/v1beta1/scripts/fixup_servicedirectory_v1beta1_keywords.py create mode 100644 owl-bot-staging/v1beta1/setup.py create mode 100644 owl-bot-staging/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 00000000..078f9e0e --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/servicedirectory/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 00000000..b87a38b8 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/servicedirectory *.py +recursive-include google/cloud/servicedirectory_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 00000000..2a61473b --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Servicedirectory 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 Servicedirectory 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/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 00000000..f684689e --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-servicedirectory 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-servicedirectory" +copyright = u"2020, 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 = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# 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-servicedirectory-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 = [ + ( + master_doc, + "google-cloud-servicedirectory.tex", + u"google-cloud-servicedirectory 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 = [ + ( + master_doc, + "google-cloud-servicedirectory", + u"Google Cloud Servicedirectory 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 = [ + ( + master_doc, + "google-cloud-servicedirectory", + u"google-cloud-servicedirectory Documentation", + author, + "google-cloud-servicedirectory", + "GAPIC library for Google Cloud Servicedirectory 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/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 00000000..cc43e5d2 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + servicedirectory_v1/services + servicedirectory_v1/types diff --git a/owl-bot-staging/v1/docs/servicedirectory_v1/lookup_service.rst b/owl-bot-staging/v1/docs/servicedirectory_v1/lookup_service.rst new file mode 100644 index 00000000..a71b7da8 --- /dev/null +++ b/owl-bot-staging/v1/docs/servicedirectory_v1/lookup_service.rst @@ -0,0 +1,6 @@ +LookupService +------------------------------- + +.. automodule:: google.cloud.servicedirectory_v1.services.lookup_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/servicedirectory_v1/registration_service.rst b/owl-bot-staging/v1/docs/servicedirectory_v1/registration_service.rst new file mode 100644 index 00000000..1f8f5330 --- /dev/null +++ b/owl-bot-staging/v1/docs/servicedirectory_v1/registration_service.rst @@ -0,0 +1,10 @@ +RegistrationService +------------------------------------- + +.. automodule:: google.cloud.servicedirectory_v1.services.registration_service + :members: + :inherited-members: + +.. automodule:: google.cloud.servicedirectory_v1.services.registration_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/servicedirectory_v1/services.rst b/owl-bot-staging/v1/docs/servicedirectory_v1/services.rst new file mode 100644 index 00000000..be303040 --- /dev/null +++ b/owl-bot-staging/v1/docs/servicedirectory_v1/services.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Servicedirectory v1 API +================================================= +.. toctree:: + :maxdepth: 2 + + lookup_service + registration_service diff --git a/owl-bot-staging/v1/docs/servicedirectory_v1/types.rst b/owl-bot-staging/v1/docs/servicedirectory_v1/types.rst new file mode 100644 index 00000000..376220b5 --- /dev/null +++ b/owl-bot-staging/v1/docs/servicedirectory_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Servicedirectory v1 API +============================================== + +.. automodule:: google.cloud.servicedirectory_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory/__init__.py new file mode 100644 index 00000000..15bed353 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory/__init__.py @@ -0,0 +1,73 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.servicedirectory_v1.services.lookup_service.client import LookupServiceClient +from google.cloud.servicedirectory_v1.services.lookup_service.async_client import LookupServiceAsyncClient +from google.cloud.servicedirectory_v1.services.registration_service.client import RegistrationServiceClient +from google.cloud.servicedirectory_v1.services.registration_service.async_client import RegistrationServiceAsyncClient + +from google.cloud.servicedirectory_v1.types.endpoint import Endpoint +from google.cloud.servicedirectory_v1.types.lookup_service import ResolveServiceRequest +from google.cloud.servicedirectory_v1.types.lookup_service import ResolveServiceResponse +from google.cloud.servicedirectory_v1.types.namespace import Namespace +from google.cloud.servicedirectory_v1.types.registration_service import CreateEndpointRequest +from google.cloud.servicedirectory_v1.types.registration_service import CreateNamespaceRequest +from google.cloud.servicedirectory_v1.types.registration_service import CreateServiceRequest +from google.cloud.servicedirectory_v1.types.registration_service import DeleteEndpointRequest +from google.cloud.servicedirectory_v1.types.registration_service import DeleteNamespaceRequest +from google.cloud.servicedirectory_v1.types.registration_service import DeleteServiceRequest +from google.cloud.servicedirectory_v1.types.registration_service import GetEndpointRequest +from google.cloud.servicedirectory_v1.types.registration_service import GetNamespaceRequest +from google.cloud.servicedirectory_v1.types.registration_service import GetServiceRequest +from google.cloud.servicedirectory_v1.types.registration_service import ListEndpointsRequest +from google.cloud.servicedirectory_v1.types.registration_service import ListEndpointsResponse +from google.cloud.servicedirectory_v1.types.registration_service import ListNamespacesRequest +from google.cloud.servicedirectory_v1.types.registration_service import ListNamespacesResponse +from google.cloud.servicedirectory_v1.types.registration_service import ListServicesRequest +from google.cloud.servicedirectory_v1.types.registration_service import ListServicesResponse +from google.cloud.servicedirectory_v1.types.registration_service import UpdateEndpointRequest +from google.cloud.servicedirectory_v1.types.registration_service import UpdateNamespaceRequest +from google.cloud.servicedirectory_v1.types.registration_service import UpdateServiceRequest +from google.cloud.servicedirectory_v1.types.service import Service + +__all__ = ('LookupServiceClient', + 'LookupServiceAsyncClient', + 'RegistrationServiceClient', + 'RegistrationServiceAsyncClient', + 'Endpoint', + 'ResolveServiceRequest', + 'ResolveServiceResponse', + 'Namespace', + 'CreateEndpointRequest', + 'CreateNamespaceRequest', + 'CreateServiceRequest', + 'DeleteEndpointRequest', + 'DeleteNamespaceRequest', + 'DeleteServiceRequest', + 'GetEndpointRequest', + 'GetNamespaceRequest', + 'GetServiceRequest', + 'ListEndpointsRequest', + 'ListEndpointsResponse', + 'ListNamespacesRequest', + 'ListNamespacesResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'UpdateEndpointRequest', + 'UpdateNamespaceRequest', + 'UpdateServiceRequest', + 'Service', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory/py.typed b/owl-bot-staging/v1/google/cloud/servicedirectory/py.typed new file mode 100644 index 00000000..6790e24b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-servicedirectory package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/__init__.py new file mode 100644 index 00000000..9160262b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/__init__.py @@ -0,0 +1,74 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .services.lookup_service import LookupServiceClient +from .services.lookup_service import LookupServiceAsyncClient +from .services.registration_service import RegistrationServiceClient +from .services.registration_service import RegistrationServiceAsyncClient + +from .types.endpoint import Endpoint +from .types.lookup_service import ResolveServiceRequest +from .types.lookup_service import ResolveServiceResponse +from .types.namespace import Namespace +from .types.registration_service import CreateEndpointRequest +from .types.registration_service import CreateNamespaceRequest +from .types.registration_service import CreateServiceRequest +from .types.registration_service import DeleteEndpointRequest +from .types.registration_service import DeleteNamespaceRequest +from .types.registration_service import DeleteServiceRequest +from .types.registration_service import GetEndpointRequest +from .types.registration_service import GetNamespaceRequest +from .types.registration_service import GetServiceRequest +from .types.registration_service import ListEndpointsRequest +from .types.registration_service import ListEndpointsResponse +from .types.registration_service import ListNamespacesRequest +from .types.registration_service import ListNamespacesResponse +from .types.registration_service import ListServicesRequest +from .types.registration_service import ListServicesResponse +from .types.registration_service import UpdateEndpointRequest +from .types.registration_service import UpdateNamespaceRequest +from .types.registration_service import UpdateServiceRequest +from .types.service import Service + +__all__ = ( + 'LookupServiceAsyncClient', + 'RegistrationServiceAsyncClient', +'CreateEndpointRequest', +'CreateNamespaceRequest', +'CreateServiceRequest', +'DeleteEndpointRequest', +'DeleteNamespaceRequest', +'DeleteServiceRequest', +'Endpoint', +'GetEndpointRequest', +'GetNamespaceRequest', +'GetServiceRequest', +'ListEndpointsRequest', +'ListEndpointsResponse', +'ListNamespacesRequest', +'ListNamespacesResponse', +'ListServicesRequest', +'ListServicesResponse', +'LookupServiceClient', +'Namespace', +'RegistrationServiceClient', +'ResolveServiceRequest', +'ResolveServiceResponse', +'Service', +'UpdateEndpointRequest', +'UpdateNamespaceRequest', +'UpdateServiceRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/gapic_metadata.json new file mode 100644 index 00000000..55647f3f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/gapic_metadata.json @@ -0,0 +1,227 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.servicedirectory_v1", + "protoPackage": "google.cloud.servicedirectory.v1", + "schema": "1.0", + "services": { + "LookupService": { + "clients": { + "grpc": { + "libraryClient": "LookupServiceClient", + "rpcs": { + "ResolveService": { + "methods": [ + "resolve_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LookupServiceAsyncClient", + "rpcs": { + "ResolveService": { + "methods": [ + "resolve_service" + ] + } + } + } + } + }, + "RegistrationService": { + "clients": { + "grpc": { + "libraryClient": "RegistrationServiceClient", + "rpcs": { + "CreateEndpoint": { + "methods": [ + "create_endpoint" + ] + }, + "CreateNamespace": { + "methods": [ + "create_namespace" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteEndpoint": { + "methods": [ + "delete_endpoint" + ] + }, + "DeleteNamespace": { + "methods": [ + "delete_namespace" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetEndpoint": { + "methods": [ + "get_endpoint" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNamespace": { + "methods": [ + "get_namespace" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListEndpoints": { + "methods": [ + "list_endpoints" + ] + }, + "ListNamespaces": { + "methods": [ + "list_namespaces" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateEndpoint": { + "methods": [ + "update_endpoint" + ] + }, + "UpdateNamespace": { + "methods": [ + "update_namespace" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RegistrationServiceAsyncClient", + "rpcs": { + "CreateEndpoint": { + "methods": [ + "create_endpoint" + ] + }, + "CreateNamespace": { + "methods": [ + "create_namespace" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteEndpoint": { + "methods": [ + "delete_endpoint" + ] + }, + "DeleteNamespace": { + "methods": [ + "delete_namespace" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetEndpoint": { + "methods": [ + "get_endpoint" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNamespace": { + "methods": [ + "get_namespace" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListEndpoints": { + "methods": [ + "list_endpoints" + ] + }, + "ListNamespaces": { + "methods": [ + "list_namespaces" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateEndpoint": { + "methods": [ + "update_endpoint" + ] + }, + "UpdateNamespace": { + "methods": [ + "update_namespace" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/py.typed b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/py.typed new file mode 100644 index 00000000..6790e24b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-servicedirectory package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py new file mode 100644 index 00000000..926753ac --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 LookupServiceClient +from .async_client import LookupServiceAsyncClient + +__all__ = ( + 'LookupServiceClient', + 'LookupServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py new file mode 100644 index 00000000..ec02058f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py @@ -0,0 +1,226 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1.types import lookup_service +from google.cloud.servicedirectory_v1.types import service +from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport +from .client import LookupServiceClient + + +class LookupServiceAsyncClient: + """Service Directory API for looking up service data at runtime.""" + + _client: LookupServiceClient + + DEFAULT_ENDPOINT = LookupServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LookupServiceClient.DEFAULT_MTLS_ENDPOINT + + endpoint_path = staticmethod(LookupServiceClient.endpoint_path) + parse_endpoint_path = staticmethod(LookupServiceClient.parse_endpoint_path) + service_path = staticmethod(LookupServiceClient.service_path) + parse_service_path = staticmethod(LookupServiceClient.parse_service_path) + common_billing_account_path = staticmethod(LookupServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LookupServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LookupServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(LookupServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(LookupServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(LookupServiceClient.parse_common_organization_path) + common_project_path = staticmethod(LookupServiceClient.common_project_path) + parse_common_project_path = staticmethod(LookupServiceClient.parse_common_project_path) + common_location_path = staticmethod(LookupServiceClient.common_location_path) + parse_common_location_path = staticmethod(LookupServiceClient.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: + LookupServiceAsyncClient: The constructed client. + """ + return LookupServiceClient.from_service_account_info.__func__(LookupServiceAsyncClient, 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: + LookupServiceAsyncClient: The constructed client. + """ + return LookupServiceClient.from_service_account_file.__func__(LookupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> LookupServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LookupServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(LookupServiceClient).get_transport_class, type(LookupServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, LookupServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lookup 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 (Union[str, ~.LookupServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = LookupServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def resolve_service(self, + request: lookup_service.ResolveServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lookup_service.ResolveServiceResponse: + r"""Returns a [service][google.cloud.servicedirectory.v1.Service] + and its associated endpoints. Resolving a service is not + considered an active developer method. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.ResolveServiceRequest`): + The request object. The request message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + Looks up a service by its name, returns the service and + its endpoints. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.servicedirectory_v1.types.ResolveServiceResponse: + The response message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + + """ + # Create or coerce a protobuf request object. + request = lookup_service.ResolveServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.resolve_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-servicedirectory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "LookupServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/client.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/client.py new file mode 100644 index 00000000..ecef1ebe --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/client.py @@ -0,0 +1,433 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +from google.cloud.servicedirectory_v1.types import lookup_service +from google.cloud.servicedirectory_v1.types import service +from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LookupServiceGrpcTransport +from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport + + +class LookupServiceClientMeta(type): + """Metaclass for the LookupService 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[LookupServiceTransport]] + _transport_registry["grpc"] = LookupServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LookupServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[LookupServiceTransport]: + """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 LookupServiceClient(metaclass=LookupServiceClientMeta): + """Service Directory API for looking up service data at runtime.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "servicedirectory.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LookupServiceClient: 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: + LookupServiceClient: 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) -> LookupServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LookupServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def endpoint_path(project: str,location: str,namespace: str,service: str,endpoint: str,) -> str: + """Returns a fully-qualified endpoint string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) + + @staticmethod + def parse_endpoint_path(path: str) -> Dict[str,str]: + """Parses a endpoint path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,namespace: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, LookupServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lookup 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 (Union[str, LookupServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, LookupServiceTransport): + # transport is a LookupServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def resolve_service(self, + request: Union[lookup_service.ResolveServiceRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lookup_service.ResolveServiceResponse: + r"""Returns a [service][google.cloud.servicedirectory.v1.Service] + and its associated endpoints. Resolving a service is not + considered an active developer method. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.ResolveServiceRequest, dict]): + The request object. The request message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + Looks up a service by its name, returns the service and + its endpoints. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.servicedirectory_v1.types.ResolveServiceResponse: + The response message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a lookup_service.ResolveServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, lookup_service.ResolveServiceRequest): + request = lookup_service.ResolveServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resolve_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-servicedirectory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "LookupServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py new file mode 100644 index 00000000..437f5631 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 LookupServiceTransport +from .grpc import LookupServiceGrpcTransport +from .grpc_asyncio import LookupServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LookupServiceTransport]] +_transport_registry['grpc'] = LookupServiceGrpcTransport +_transport_registry['grpc_asyncio'] = LookupServiceGrpcAsyncIOTransport + +__all__ = ( + 'LookupServiceTransport', + 'LookupServiceGrpcTransport', + 'LookupServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py new file mode 100644 index 00000000..68b2b195 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py @@ -0,0 +1,177 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1.types import lookup_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-servicedirectory', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class LookupServiceTransport(abc.ABC): + """Abstract transport class for LookupService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'servicedirectory.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.resolve_service: gapic_v1.method.wrap_method( + self.resolve_service, + 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 resolve_service(self) -> Callable[ + [lookup_service.ResolveServiceRequest], + Union[ + lookup_service.ResolveServiceResponse, + Awaitable[lookup_service.ResolveServiceResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'LookupServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py new file mode 100644 index 00000000..283755da --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py @@ -0,0 +1,256 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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.servicedirectory_v1.types import lookup_service +from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO + + +class LookupServiceGrpcTransport(LookupServiceTransport): + """gRPC backend transport for LookupService. + + Service Directory API for looking up service data at runtime. + + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 resolve_service(self) -> Callable[ + [lookup_service.ResolveServiceRequest], + lookup_service.ResolveServiceResponse]: + r"""Return a callable for the resolve service method over gRPC. + + Returns a [service][google.cloud.servicedirectory.v1.Service] + and its associated endpoints. Resolving a service is not + considered an active developer method. + + Returns: + Callable[[~.ResolveServiceRequest], + ~.ResolveServiceResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'resolve_service' not in self._stubs: + self._stubs['resolve_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.LookupService/ResolveService', + request_serializer=lookup_service.ResolveServiceRequest.serialize, + response_deserializer=lookup_service.ResolveServiceResponse.deserialize, + ) + return self._stubs['resolve_service'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'LookupServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..d20b82e4 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py @@ -0,0 +1,261 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.servicedirectory_v1.types import lookup_service +from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LookupServiceGrpcTransport + + +class LookupServiceGrpcAsyncIOTransport(LookupServiceTransport): + """gRPC AsyncIO backend transport for LookupService. + + Service Directory API for looking up service data at runtime. + + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def resolve_service(self) -> Callable[ + [lookup_service.ResolveServiceRequest], + Awaitable[lookup_service.ResolveServiceResponse]]: + r"""Return a callable for the resolve service method over gRPC. + + Returns a [service][google.cloud.servicedirectory.v1.Service] + and its associated endpoints. Resolving a service is not + considered an active developer method. + + Returns: + Callable[[~.ResolveServiceRequest], + Awaitable[~.ResolveServiceResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'resolve_service' not in self._stubs: + self._stubs['resolve_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.LookupService/ResolveService', + request_serializer=lookup_service.ResolveServiceRequest.serialize, + response_deserializer=lookup_service.ResolveServiceResponse.deserialize, + ) + return self._stubs['resolve_service'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'LookupServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/__init__.py new file mode 100644 index 00000000..5097508c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 RegistrationServiceClient +from .async_client import RegistrationServiceAsyncClient + +__all__ = ( + 'RegistrationServiceClient', + 'RegistrationServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/async_client.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/async_client.py new file mode 100644 index 00000000..b2aa3e9e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/async_client.py @@ -0,0 +1,1736 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1.services.registration_service import pagers +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport +from .client import RegistrationServiceClient + + +class RegistrationServiceAsyncClient: + """Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1.Service] resources, + named ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, + named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + """ + + _client: RegistrationServiceClient + + DEFAULT_ENDPOINT = RegistrationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + + endpoint_path = staticmethod(RegistrationServiceClient.endpoint_path) + parse_endpoint_path = staticmethod(RegistrationServiceClient.parse_endpoint_path) + namespace_path = staticmethod(RegistrationServiceClient.namespace_path) + parse_namespace_path = staticmethod(RegistrationServiceClient.parse_namespace_path) + service_path = staticmethod(RegistrationServiceClient.service_path) + parse_service_path = staticmethod(RegistrationServiceClient.parse_service_path) + common_billing_account_path = staticmethod(RegistrationServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RegistrationServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RegistrationServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(RegistrationServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(RegistrationServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(RegistrationServiceClient.parse_common_organization_path) + common_project_path = staticmethod(RegistrationServiceClient.common_project_path) + parse_common_project_path = staticmethod(RegistrationServiceClient.parse_common_project_path) + common_location_path = staticmethod(RegistrationServiceClient.common_location_path) + parse_common_location_path = staticmethod(RegistrationServiceClient.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: + RegistrationServiceAsyncClient: The constructed client. + """ + return RegistrationServiceClient.from_service_account_info.__func__(RegistrationServiceAsyncClient, 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: + RegistrationServiceAsyncClient: The constructed client. + """ + return RegistrationServiceClient.from_service_account_file.__func__(RegistrationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RegistrationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegistrationServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RegistrationServiceClient).get_transport_class, type(RegistrationServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, RegistrationServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the registration 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 (Union[str, ~.RegistrationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RegistrationServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_namespace(self, + request: registration_service.CreateNamespaceRequest = None, + *, + parent: str = None, + namespace: gcs_namespace.Namespace = None, + namespace_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Creates a namespace, and returns the new Namespace. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.CreateNamespaceRequest`): + The request object. The request message for + [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1.RegistrationService.CreateNamespace]. + parent (:class:`str`): + Required. The resource name of the + project and location the namespace will + be created in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace (:class:`google.cloud.servicedirectory_v1.types.Namespace`): + Required. A namespace with initial + fields set. + + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``namespace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, namespace, namespace_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.CreateNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if namespace is not None: + request.namespace = namespace + if namespace_id is not None: + request.namespace_id = namespace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_namespaces(self, + request: registration_service.ListNamespacesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNamespacesAsyncPager: + r"""Lists all namespaces. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.ListNamespacesRequest`): + The request object. The request message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + parent (:class:`str`): + Required. The resource name of the + project and location whose namespaces + we'd like to list. + + 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.servicedirectory_v1.services.registration_service.pagers.ListNamespacesAsyncPager: + The response message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.ListNamespacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_namespaces, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListNamespacesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_namespace(self, + request: registration_service.GetNamespaceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> namespace.Namespace: + r"""Gets a namespace. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.GetNamespaceRequest`): + The request object. The request message for + [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1.RegistrationService.GetNamespace]. + name (:class:`str`): + Required. The name of the namespace + to retrieve. + + 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.servicedirectory_v1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.GetNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_namespace(self, + request: registration_service.UpdateNamespaceRequest = None, + *, + namespace: gcs_namespace.Namespace = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Updates a namespace. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.UpdateNamespaceRequest`): + The request object. The request message for + [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1.RegistrationService.UpdateNamespace]. + namespace (:class:`google.cloud.servicedirectory_v1.types.Namespace`): + Required. The updated namespace. + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([namespace, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.UpdateNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if namespace is not None: + request.namespace = namespace + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("namespace.name", request.namespace.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_namespace(self, + request: registration_service.DeleteNamespaceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.DeleteNamespaceRequest`): + The request object. The request message for + [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1.RegistrationService.DeleteNamespace]. + name (:class:`str`): + Required. The name of the namespace + to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.DeleteNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_service(self, + request: registration_service.CreateServiceRequest = None, + *, + parent: str = None, + service: gcs_service.Service = None, + service_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Creates a service, and returns the new Service. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.CreateServiceRequest`): + The request object. The request message for + [RegistrationService.CreateService][google.cloud.servicedirectory.v1.RegistrationService.CreateService]. + parent (:class:`str`): + Required. The resource name of the + namespace this service will belong to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (:class:`google.cloud.servicedirectory_v1.types.Service`): + Required. A service with initial + fields set. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.CreateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_services(self, + request: registration_service.ListServicesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesAsyncPager: + r"""Lists all services belonging to a namespace. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.ListServicesRequest`): + The request object. The request message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + parent (:class:`str`): + Required. The resource name of the + namespace whose services we'd like to + list. + + 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.servicedirectory_v1.services.registration_service.pagers.ListServicesAsyncPager: + The response message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.ListServicesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_services, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServicesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service(self, + request: registration_service.GetServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets a service. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.GetServiceRequest`): + The request object. The request message for + [RegistrationService.GetService][google.cloud.servicedirectory.v1.RegistrationService.GetService]. + This should not be used for looking up a service. + Insead, use the `resolve` method as it will contain all + endpoints and associated metadata. + name (:class:`str`): + Required. The name of the service to + get. + + 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.servicedirectory_v1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.GetServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_service(self, + request: registration_service.UpdateServiceRequest = None, + *, + service: gcs_service.Service = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Updates a service. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.UpdateServiceRequest`): + The request object. The request message for + [RegistrationService.UpdateService][google.cloud.servicedirectory.v1.RegistrationService.UpdateService]. + service (:class:`google.cloud.servicedirectory_v1.types.Service`): + Required. The updated service. + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.UpdateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_service(self, + request: registration_service.DeleteServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a service. This also deletes all endpoints + associated with the service. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.DeleteServiceRequest`): + The request object. The request message for + [RegistrationService.DeleteService][google.cloud.servicedirectory.v1.RegistrationService.DeleteService]. + name (:class:`str`): + Required. The name of the service to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.DeleteServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_endpoint(self, + request: registration_service.CreateEndpointRequest = None, + *, + parent: str = None, + endpoint: gcs_endpoint.Endpoint = None, + endpoint_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Creates a endpoint, and returns the new Endpoint. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.CreateEndpointRequest`): + The request object. The request message for + [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.CreateEndpoint]. + parent (:class:`str`): + Required. The resource name of the + service that this endpoint provides. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint (:class:`google.cloud.servicedirectory_v1.types.Endpoint`): + Required. A endpoint with initial + fields set. + + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, endpoint, endpoint_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.CreateEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if endpoint is not None: + request.endpoint = endpoint + if endpoint_id is not None: + request.endpoint_id = endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_endpoints(self, + request: registration_service.ListEndpointsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEndpointsAsyncPager: + r"""Lists all endpoints. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.ListEndpointsRequest`): + The request object. The request message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + parent (:class:`str`): + Required. The resource name of the + service whose endpoints we'd like to + list. + + 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.servicedirectory_v1.services.registration_service.pagers.ListEndpointsAsyncPager: + The response message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.ListEndpointsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_endpoints, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEndpointsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_endpoint(self, + request: registration_service.GetEndpointRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint.Endpoint: + r"""Gets a endpoint. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.GetEndpointRequest`): + The request object. The request message for + [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1.RegistrationService.GetEndpoint]. + This should not be used to lookup endpoints at runtime. + Instead, use the `resolve` method. + name (:class:`str`): + Required. The name of the endpoint to + get. + + 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.servicedirectory_v1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.GetEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_endpoint(self, + request: registration_service.UpdateEndpointRequest = None, + *, + endpoint: gcs_endpoint.Endpoint = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Updates a endpoint. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.UpdateEndpointRequest`): + The request object. The request message for + [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.UpdateEndpoint]. + endpoint (:class:`google.cloud.servicedirectory_v1.types.Endpoint`): + Required. The updated endpoint. + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([endpoint, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.UpdateEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if endpoint is not None: + request.endpoint = endpoint + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("endpoint.name", request.endpoint.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_endpoint(self, + request: registration_service.DeleteEndpointRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a endpoint. + + Args: + request (:class:`google.cloud.servicedirectory_v1.types.DeleteEndpointRequest`): + The request object. The request message for + [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1.RegistrationService.DeleteEndpoint]. + name (:class:`str`): + Required. The name of the endpoint to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.DeleteEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_iam_policy(self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM Policy for a resource (namespace or + service only). + + Args: + request (:class:`google.iam.v1.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: + google.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy(self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM Policy for a resource (namespace or + service only). + + Args: + request (:class:`google.iam.v1.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: + google.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions(self, + request: iam_policy_pb2.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests IAM permissions for a resource (namespace or + service only). + + Args: + request (:class:`google.iam.v1.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: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-servicedirectory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "RegistrationServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/client.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/client.py new file mode 100644 index 00000000..a64d2f62 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/client.py @@ -0,0 +1,1948 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +from google.cloud.servicedirectory_v1.services.registration_service import pagers +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RegistrationServiceGrpcTransport +from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport + + +class RegistrationServiceClientMeta(type): + """Metaclass for the RegistrationService 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[RegistrationServiceTransport]] + _transport_registry["grpc"] = RegistrationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RegistrationServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[RegistrationServiceTransport]: + """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 RegistrationServiceClient(metaclass=RegistrationServiceClientMeta): + """Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1.Service] resources, + named ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, + named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "servicedirectory.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegistrationServiceClient: 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: + RegistrationServiceClient: 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) -> RegistrationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegistrationServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def endpoint_path(project: str,location: str,namespace: str,service: str,endpoint: str,) -> str: + """Returns a fully-qualified endpoint string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) + + @staticmethod + def parse_endpoint_path(path: str) -> Dict[str,str]: + """Parses a endpoint path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def namespace_path(project: str,location: str,namespace: str,) -> str: + """Returns a fully-qualified namespace string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}".format(project=project, location=location, namespace=namespace, ) + + @staticmethod + def parse_namespace_path(path: str) -> Dict[str,str]: + """Parses a namespace path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,namespace: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RegistrationServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the registration 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 (Union[str, RegistrationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RegistrationServiceTransport): + # transport is a RegistrationServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_namespace(self, + request: Union[registration_service.CreateNamespaceRequest, dict] = None, + *, + parent: str = None, + namespace: gcs_namespace.Namespace = None, + namespace_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Creates a namespace, and returns the new Namespace. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.CreateNamespaceRequest, dict]): + The request object. The request message for + [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1.RegistrationService.CreateNamespace]. + parent (str): + Required. The resource name of the + project and location the namespace will + be created in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace (google.cloud.servicedirectory_v1.types.Namespace): + Required. A namespace with initial + fields set. + + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace_id (str): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``namespace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, namespace, namespace_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateNamespaceRequest): + request = registration_service.CreateNamespaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if namespace is not None: + request.namespace = namespace + if namespace_id is not None: + request.namespace_id = namespace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_namespaces(self, + request: Union[registration_service.ListNamespacesRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNamespacesPager: + r"""Lists all namespaces. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.ListNamespacesRequest, dict]): + The request object. The request message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + parent (str): + Required. The resource name of the + project and location whose namespaces + we'd like to list. + + 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.servicedirectory_v1.services.registration_service.pagers.ListNamespacesPager: + The response message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListNamespacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListNamespacesRequest): + request = registration_service.ListNamespacesRequest(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_namespaces] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListNamespacesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_namespace(self, + request: Union[registration_service.GetNamespaceRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> namespace.Namespace: + r"""Gets a namespace. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.GetNamespaceRequest, dict]): + The request object. The request message for + [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1.RegistrationService.GetNamespace]. + name (str): + Required. The name of the namespace + to retrieve. + + 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.servicedirectory_v1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetNamespaceRequest): + request = registration_service.GetNamespaceRequest(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_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_namespace(self, + request: Union[registration_service.UpdateNamespaceRequest, dict] = None, + *, + namespace: gcs_namespace.Namespace = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Updates a namespace. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.UpdateNamespaceRequest, dict]): + The request object. The request message for + [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1.RegistrationService.UpdateNamespace]. + namespace (google.cloud.servicedirectory_v1.types.Namespace): + Required. The updated namespace. + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([namespace, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateNamespaceRequest): + request = registration_service.UpdateNamespaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if namespace is not None: + request.namespace = namespace + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("namespace.name", request.namespace.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_namespace(self, + request: Union[registration_service.DeleteNamespaceRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.DeleteNamespaceRequest, dict]): + The request object. The request message for + [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1.RegistrationService.DeleteNamespace]. + name (str): + Required. The name of the namespace + to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteNamespaceRequest): + request = registration_service.DeleteNamespaceRequest(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_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_service(self, + request: Union[registration_service.CreateServiceRequest, dict] = None, + *, + parent: str = None, + service: gcs_service.Service = None, + service_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Creates a service, and returns the new Service. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.CreateServiceRequest, dict]): + The request object. The request message for + [RegistrationService.CreateService][google.cloud.servicedirectory.v1.RegistrationService.CreateService]. + parent (str): + Required. The resource name of the + namespace this service will belong to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (google.cloud.servicedirectory_v1.types.Service): + Required. A service with initial + fields set. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (str): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateServiceRequest): + request = registration_service.CreateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_services(self, + request: Union[registration_service.ListServicesRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesPager: + r"""Lists all services belonging to a namespace. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.ListServicesRequest, dict]): + The request object. The request message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + parent (str): + Required. The resource name of the + namespace whose services we'd like to + list. + + 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.servicedirectory_v1.services.registration_service.pagers.ListServicesPager: + The response message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListServicesRequest): + request = registration_service.ListServicesRequest(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_services] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServicesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service(self, + request: Union[registration_service.GetServiceRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets a service. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.GetServiceRequest, dict]): + The request object. The request message for + [RegistrationService.GetService][google.cloud.servicedirectory.v1.RegistrationService.GetService]. + This should not be used for looking up a service. + Insead, use the `resolve` method as it will contain all + endpoints and associated metadata. + name (str): + Required. The name of the service to + get. + + 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.servicedirectory_v1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetServiceRequest): + request = registration_service.GetServiceRequest(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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_service(self, + request: Union[registration_service.UpdateServiceRequest, dict] = None, + *, + service: gcs_service.Service = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Updates a service. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.UpdateServiceRequest, dict]): + The request object. The request message for + [RegistrationService.UpdateService][google.cloud.servicedirectory.v1.RegistrationService.UpdateService]. + service (google.cloud.servicedirectory_v1.types.Service): + Required. The updated service. + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateServiceRequest): + request = registration_service.UpdateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_service(self, + request: Union[registration_service.DeleteServiceRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a service. This also deletes all endpoints + associated with the service. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.DeleteServiceRequest, dict]): + The request object. The request message for + [RegistrationService.DeleteService][google.cloud.servicedirectory.v1.RegistrationService.DeleteService]. + name (str): + Required. The name of the service to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteServiceRequest): + request = registration_service.DeleteServiceRequest(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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_endpoint(self, + request: Union[registration_service.CreateEndpointRequest, dict] = None, + *, + parent: str = None, + endpoint: gcs_endpoint.Endpoint = None, + endpoint_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Creates a endpoint, and returns the new Endpoint. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.CreateEndpointRequest, dict]): + The request object. The request message for + [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.CreateEndpoint]. + parent (str): + Required. The resource name of the + service that this endpoint provides. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint (google.cloud.servicedirectory_v1.types.Endpoint): + Required. A endpoint with initial + fields set. + + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_id (str): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, endpoint, endpoint_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateEndpointRequest): + request = registration_service.CreateEndpointRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if endpoint is not None: + request.endpoint = endpoint + if endpoint_id is not None: + request.endpoint_id = endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_endpoints(self, + request: Union[registration_service.ListEndpointsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEndpointsPager: + r"""Lists all endpoints. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.ListEndpointsRequest, dict]): + The request object. The request message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + parent (str): + Required. The resource name of the + service whose endpoints we'd like to + list. + + 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.servicedirectory_v1.services.registration_service.pagers.ListEndpointsPager: + The response message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListEndpointsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListEndpointsRequest): + request = registration_service.ListEndpointsRequest(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_endpoints] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEndpointsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_endpoint(self, + request: Union[registration_service.GetEndpointRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint.Endpoint: + r"""Gets a endpoint. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.GetEndpointRequest, dict]): + The request object. The request message for + [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1.RegistrationService.GetEndpoint]. + This should not be used to lookup endpoints at runtime. + Instead, use the `resolve` method. + name (str): + Required. The name of the endpoint to + get. + + 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.servicedirectory_v1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetEndpointRequest): + request = registration_service.GetEndpointRequest(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_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_endpoint(self, + request: Union[registration_service.UpdateEndpointRequest, dict] = None, + *, + endpoint: gcs_endpoint.Endpoint = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Updates a endpoint. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.UpdateEndpointRequest, dict]): + The request object. The request message for + [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.UpdateEndpoint]. + endpoint (google.cloud.servicedirectory_v1.types.Endpoint): + Required. The updated endpoint. + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([endpoint, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateEndpointRequest): + request = registration_service.UpdateEndpointRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if endpoint is not None: + request.endpoint = endpoint + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("endpoint.name", request.endpoint.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_endpoint(self, + request: Union[registration_service.DeleteEndpointRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a endpoint. + + Args: + request (Union[google.cloud.servicedirectory_v1.types.DeleteEndpointRequest, dict]): + The request object. The request message for + [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1.RegistrationService.DeleteEndpoint]. + name (str): + Required. The name of the endpoint to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteEndpointRequest): + request = registration_service.DeleteEndpointRequest(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_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM Policy for a resource (namespace or + service only). + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + 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: + google.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy(self, + request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM Policy for a resource (namespace or + service only). + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + 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: + google.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions(self, + request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests IAM permissions for a resource (namespace or + service only). + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + 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: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-servicedirectory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "RegistrationServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/pagers.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/pagers.py new file mode 100644 index 00000000..682e1d7c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/pagers.py @@ -0,0 +1,387 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service + + +class ListNamespacesPager: + """A pager for iterating through ``list_namespaces`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1.types.ListNamespacesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``namespaces`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNamespaces`` requests and continue to iterate + through the ``namespaces`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1.types.ListNamespacesResponse` + 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[..., registration_service.ListNamespacesResponse], + request: registration_service.ListNamespacesRequest, + response: registration_service.ListNamespacesResponse, + *, + 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.servicedirectory_v1.types.ListNamespacesRequest): + The initial request object. + response (google.cloud.servicedirectory_v1.types.ListNamespacesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListNamespacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registration_service.ListNamespacesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[namespace.Namespace]: + for page in self.pages: + yield from page.namespaces + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNamespacesAsyncPager: + """A pager for iterating through ``list_namespaces`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1.types.ListNamespacesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``namespaces`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNamespaces`` requests and continue to iterate + through the ``namespaces`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1.types.ListNamespacesResponse` + 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[registration_service.ListNamespacesResponse]], + request: registration_service.ListNamespacesRequest, + response: registration_service.ListNamespacesResponse, + *, + 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.servicedirectory_v1.types.ListNamespacesRequest): + The initial request object. + response (google.cloud.servicedirectory_v1.types.ListNamespacesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListNamespacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registration_service.ListNamespacesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[namespace.Namespace]: + async def async_generator(): + async for page in self.pages: + for response in page.namespaces: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServicesPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1.types.ListServicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1.types.ListServicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., registration_service.ListServicesResponse], + request: registration_service.ListServicesRequest, + response: registration_service.ListServicesResponse, + *, + 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.servicedirectory_v1.types.ListServicesRequest): + The initial request object. + response (google.cloud.servicedirectory_v1.types.ListServicesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registration_service.ListServicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[service.Service]: + for page in self.pages: + yield from page.services + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServicesAsyncPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1.types.ListServicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1.types.ListServicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[registration_service.ListServicesResponse]], + request: registration_service.ListServicesRequest, + response: registration_service.ListServicesResponse, + *, + 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.servicedirectory_v1.types.ListServicesRequest): + The initial request object. + response (google.cloud.servicedirectory_v1.types.ListServicesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registration_service.ListServicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[service.Service]: + async def async_generator(): + async for page in self.pages: + for response in page.services: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEndpointsPager: + """A pager for iterating through ``list_endpoints`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1.types.ListEndpointsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``endpoints`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEndpoints`` requests and continue to iterate + through the ``endpoints`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1.types.ListEndpointsResponse` + 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[..., registration_service.ListEndpointsResponse], + request: registration_service.ListEndpointsRequest, + response: registration_service.ListEndpointsResponse, + *, + 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.servicedirectory_v1.types.ListEndpointsRequest): + The initial request object. + response (google.cloud.servicedirectory_v1.types.ListEndpointsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListEndpointsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registration_service.ListEndpointsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[endpoint.Endpoint]: + for page in self.pages: + yield from page.endpoints + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEndpointsAsyncPager: + """A pager for iterating through ``list_endpoints`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1.types.ListEndpointsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``endpoints`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEndpoints`` requests and continue to iterate + through the ``endpoints`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1.types.ListEndpointsResponse` + 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[registration_service.ListEndpointsResponse]], + request: registration_service.ListEndpointsRequest, + response: registration_service.ListEndpointsResponse, + *, + 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.servicedirectory_v1.types.ListEndpointsRequest): + The initial request object. + response (google.cloud.servicedirectory_v1.types.ListEndpointsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListEndpointsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registration_service.ListEndpointsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[endpoint.Endpoint]: + async def async_generator(): + async for page in self.pages: + for response in page.endpoints: + 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/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py new file mode 100644 index 00000000..a584bf16 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 RegistrationServiceTransport +from .grpc import RegistrationServiceGrpcTransport +from .grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RegistrationServiceTransport]] +_transport_registry['grpc'] = RegistrationServiceGrpcTransport +_transport_registry['grpc_asyncio'] = RegistrationServiceGrpcAsyncIOTransport + +__all__ = ( + 'RegistrationServiceTransport', + 'RegistrationServiceGrpcTransport', + 'RegistrationServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py new file mode 100644 index 00000000..0a8e3d13 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py @@ -0,0 +1,424 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-servicedirectory', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class RegistrationServiceTransport(abc.ABC): + """Abstract transport class for RegistrationService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'servicedirectory.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_namespace: gapic_v1.method.wrap_method( + self.create_namespace, + default_timeout=None, + client_info=client_info, + ), + self.list_namespaces: gapic_v1.method.wrap_method( + self.list_namespaces, + default_timeout=None, + client_info=client_info, + ), + self.get_namespace: gapic_v1.method.wrap_method( + self.get_namespace, + default_timeout=None, + client_info=client_info, + ), + self.update_namespace: gapic_v1.method.wrap_method( + self.update_namespace, + default_timeout=None, + client_info=client_info, + ), + self.delete_namespace: gapic_v1.method.wrap_method( + self.delete_namespace, + default_timeout=None, + client_info=client_info, + ), + self.create_service: gapic_v1.method.wrap_method( + self.create_service, + default_timeout=None, + client_info=client_info, + ), + self.list_services: gapic_v1.method.wrap_method( + self.list_services, + default_timeout=None, + client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, + default_timeout=None, + client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, + default_timeout=None, + client_info=client_info, + ), + self.delete_service: gapic_v1.method.wrap_method( + self.delete_service, + default_timeout=None, + client_info=client_info, + ), + self.create_endpoint: gapic_v1.method.wrap_method( + self.create_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.list_endpoints: gapic_v1.method.wrap_method( + self.list_endpoints, + default_timeout=None, + client_info=client_info, + ), + self.get_endpoint: gapic_v1.method.wrap_method( + self.get_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.update_endpoint: gapic_v1.method.wrap_method( + self.update_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.delete_endpoint: gapic_v1.method.wrap_method( + self.delete_endpoint, + 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, + ), + } + + 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 create_namespace(self) -> Callable[ + [registration_service.CreateNamespaceRequest], + Union[ + gcs_namespace.Namespace, + Awaitable[gcs_namespace.Namespace] + ]]: + raise NotImplementedError() + + @property + def list_namespaces(self) -> Callable[ + [registration_service.ListNamespacesRequest], + Union[ + registration_service.ListNamespacesResponse, + Awaitable[registration_service.ListNamespacesResponse] + ]]: + raise NotImplementedError() + + @property + def get_namespace(self) -> Callable[ + [registration_service.GetNamespaceRequest], + Union[ + namespace.Namespace, + Awaitable[namespace.Namespace] + ]]: + raise NotImplementedError() + + @property + def update_namespace(self) -> Callable[ + [registration_service.UpdateNamespaceRequest], + Union[ + gcs_namespace.Namespace, + Awaitable[gcs_namespace.Namespace] + ]]: + raise NotImplementedError() + + @property + def delete_namespace(self) -> Callable[ + [registration_service.DeleteNamespaceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_service(self) -> Callable[ + [registration_service.CreateServiceRequest], + Union[ + gcs_service.Service, + Awaitable[gcs_service.Service] + ]]: + raise NotImplementedError() + + @property + def list_services(self) -> Callable[ + [registration_service.ListServicesRequest], + Union[ + registration_service.ListServicesResponse, + Awaitable[registration_service.ListServicesResponse] + ]]: + raise NotImplementedError() + + @property + def get_service(self) -> Callable[ + [registration_service.GetServiceRequest], + Union[ + service.Service, + Awaitable[service.Service] + ]]: + raise NotImplementedError() + + @property + def update_service(self) -> Callable[ + [registration_service.UpdateServiceRequest], + Union[ + gcs_service.Service, + Awaitable[gcs_service.Service] + ]]: + raise NotImplementedError() + + @property + def delete_service(self) -> Callable[ + [registration_service.DeleteServiceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_endpoint(self) -> Callable[ + [registration_service.CreateEndpointRequest], + Union[ + gcs_endpoint.Endpoint, + Awaitable[gcs_endpoint.Endpoint] + ]]: + raise NotImplementedError() + + @property + def list_endpoints(self) -> Callable[ + [registration_service.ListEndpointsRequest], + Union[ + registration_service.ListEndpointsResponse, + Awaitable[registration_service.ListEndpointsResponse] + ]]: + raise NotImplementedError() + + @property + def get_endpoint(self) -> Callable[ + [registration_service.GetEndpointRequest], + Union[ + endpoint.Endpoint, + Awaitable[endpoint.Endpoint] + ]]: + raise NotImplementedError() + + @property + def update_endpoint(self) -> Callable[ + [registration_service.UpdateEndpointRequest], + Union[ + gcs_endpoint.Endpoint, + Awaitable[gcs_endpoint.Endpoint] + ]]: + raise NotImplementedError() + + @property + def delete_endpoint(self) -> Callable[ + [registration_service.DeleteEndpointRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + 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 set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + 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() + + +__all__ = ( + 'RegistrationServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py new file mode 100644 index 00000000..a90023c2 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py @@ -0,0 +1,724 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO + + +class RegistrationServiceGrpcTransport(RegistrationServiceTransport): + """gRPC backend transport for RegistrationService. + + Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1.Service] resources, + named ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, + named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_namespace(self) -> Callable[ + [registration_service.CreateNamespaceRequest], + gcs_namespace.Namespace]: + r"""Return a callable for the create namespace method over gRPC. + + Creates a namespace, and returns the new Namespace. + + Returns: + Callable[[~.CreateNamespaceRequest], + ~.Namespace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['create_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/CreateNamespace', + request_serializer=registration_service.CreateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs['create_namespace'] + + @property + def list_namespaces(self) -> Callable[ + [registration_service.ListNamespacesRequest], + registration_service.ListNamespacesResponse]: + r"""Return a callable for the list namespaces method over gRPC. + + Lists all namespaces. + + Returns: + Callable[[~.ListNamespacesRequest], + ~.ListNamespacesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespaces' not in self._stubs: + self._stubs['list_namespaces'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/ListNamespaces', + request_serializer=registration_service.ListNamespacesRequest.serialize, + response_deserializer=registration_service.ListNamespacesResponse.deserialize, + ) + return self._stubs['list_namespaces'] + + @property + def get_namespace(self) -> Callable[ + [registration_service.GetNamespaceRequest], + namespace.Namespace]: + r"""Return a callable for the get namespace method over gRPC. + + Gets a namespace. + + Returns: + Callable[[~.GetNamespaceRequest], + ~.Namespace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['get_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/GetNamespace', + request_serializer=registration_service.GetNamespaceRequest.serialize, + response_deserializer=namespace.Namespace.deserialize, + ) + return self._stubs['get_namespace'] + + @property + def update_namespace(self) -> Callable[ + [registration_service.UpdateNamespaceRequest], + gcs_namespace.Namespace]: + r"""Return a callable for the update namespace method over gRPC. + + Updates a namespace. + + Returns: + Callable[[~.UpdateNamespaceRequest], + ~.Namespace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['update_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/UpdateNamespace', + request_serializer=registration_service.UpdateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs['update_namespace'] + + @property + def delete_namespace(self) -> Callable[ + [registration_service.DeleteNamespaceRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete namespace method over gRPC. + + Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Returns: + Callable[[~.DeleteNamespaceRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_namespace' not in self._stubs: + self._stubs['delete_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/DeleteNamespace', + request_serializer=registration_service.DeleteNamespaceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_namespace'] + + @property + def create_service(self) -> Callable[ + [registration_service.CreateServiceRequest], + gcs_service.Service]: + r"""Return a callable for the create service method over gRPC. + + Creates a service, and returns the new Service. + + Returns: + Callable[[~.CreateServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/CreateService', + request_serializer=registration_service.CreateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs['create_service'] + + @property + def list_services(self) -> Callable[ + [registration_service.ListServicesRequest], + registration_service.ListServicesResponse]: + r"""Return a callable for the list services method over gRPC. + + Lists all services belonging to a namespace. + + Returns: + Callable[[~.ListServicesRequest], + ~.ListServicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/ListServices', + request_serializer=registration_service.ListServicesRequest.serialize, + response_deserializer=registration_service.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [registration_service.GetServiceRequest], + service.Service]: + r"""Return a callable for the get service method over gRPC. + + Gets a service. + + Returns: + Callable[[~.GetServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/GetService', + request_serializer=registration_service.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def update_service(self) -> Callable[ + [registration_service.UpdateServiceRequest], + gcs_service.Service]: + r"""Return a callable for the update service method over gRPC. + + Updates a service. + + Returns: + Callable[[~.UpdateServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/UpdateService', + request_serializer=registration_service.UpdateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [registration_service.DeleteServiceRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a service. This also deletes all endpoints + associated with the service. + + Returns: + Callable[[~.DeleteServiceRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/DeleteService', + request_serializer=registration_service.DeleteServiceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_service'] + + @property + def create_endpoint(self) -> Callable[ + [registration_service.CreateEndpointRequest], + gcs_endpoint.Endpoint]: + r"""Return a callable for the create endpoint method over gRPC. + + Creates a endpoint, and returns the new Endpoint. + + Returns: + Callable[[~.CreateEndpointRequest], + ~.Endpoint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['create_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/CreateEndpoint', + request_serializer=registration_service.CreateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs['create_endpoint'] + + @property + def list_endpoints(self) -> Callable[ + [registration_service.ListEndpointsRequest], + registration_service.ListEndpointsResponse]: + r"""Return a callable for the list endpoints method over gRPC. + + Lists all endpoints. + + Returns: + Callable[[~.ListEndpointsRequest], + ~.ListEndpointsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoints' not in self._stubs: + self._stubs['list_endpoints'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/ListEndpoints', + request_serializer=registration_service.ListEndpointsRequest.serialize, + response_deserializer=registration_service.ListEndpointsResponse.deserialize, + ) + return self._stubs['list_endpoints'] + + @property + def get_endpoint(self) -> Callable[ + [registration_service.GetEndpointRequest], + endpoint.Endpoint]: + r"""Return a callable for the get endpoint method over gRPC. + + Gets a endpoint. + + Returns: + Callable[[~.GetEndpointRequest], + ~.Endpoint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['get_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/GetEndpoint', + request_serializer=registration_service.GetEndpointRequest.serialize, + response_deserializer=endpoint.Endpoint.deserialize, + ) + return self._stubs['get_endpoint'] + + @property + def update_endpoint(self) -> Callable[ + [registration_service.UpdateEndpointRequest], + gcs_endpoint.Endpoint]: + r"""Return a callable for the update endpoint method over gRPC. + + Updates a endpoint. + + Returns: + Callable[[~.UpdateEndpointRequest], + ~.Endpoint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['update_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/UpdateEndpoint', + request_serializer=registration_service.UpdateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs['update_endpoint'] + + @property + def delete_endpoint(self) -> Callable[ + [registration_service.DeleteEndpointRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete endpoint method over gRPC. + + Deletes a endpoint. + + Returns: + Callable[[~.DeleteEndpointRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_endpoint' not in self._stubs: + self._stubs['delete_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/DeleteEndpoint', + request_serializer=registration_service.DeleteEndpointRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_endpoint'] + + @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 Policy for a resource (namespace or + service only). + + 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.cloud.servicedirectory.v1.RegistrationService/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 Policy for a resource (namespace or + service only). + + 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.cloud.servicedirectory.v1.RegistrationService/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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 IAM permissions for a resource (namespace or + service only). + + 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.cloud.servicedirectory.v1.RegistrationService/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'RegistrationServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..c0ebc5ac --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py @@ -0,0 +1,729 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RegistrationServiceGrpcTransport + + +class RegistrationServiceGrpcAsyncIOTransport(RegistrationServiceTransport): + """gRPC AsyncIO backend transport for RegistrationService. + + Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1.Service] resources, + named ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, + named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_namespace(self) -> Callable[ + [registration_service.CreateNamespaceRequest], + Awaitable[gcs_namespace.Namespace]]: + r"""Return a callable for the create namespace method over gRPC. + + Creates a namespace, and returns the new Namespace. + + Returns: + Callable[[~.CreateNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['create_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/CreateNamespace', + request_serializer=registration_service.CreateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs['create_namespace'] + + @property + def list_namespaces(self) -> Callable[ + [registration_service.ListNamespacesRequest], + Awaitable[registration_service.ListNamespacesResponse]]: + r"""Return a callable for the list namespaces method over gRPC. + + Lists all namespaces. + + Returns: + Callable[[~.ListNamespacesRequest], + Awaitable[~.ListNamespacesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespaces' not in self._stubs: + self._stubs['list_namespaces'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/ListNamespaces', + request_serializer=registration_service.ListNamespacesRequest.serialize, + response_deserializer=registration_service.ListNamespacesResponse.deserialize, + ) + return self._stubs['list_namespaces'] + + @property + def get_namespace(self) -> Callable[ + [registration_service.GetNamespaceRequest], + Awaitable[namespace.Namespace]]: + r"""Return a callable for the get namespace method over gRPC. + + Gets a namespace. + + Returns: + Callable[[~.GetNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['get_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/GetNamespace', + request_serializer=registration_service.GetNamespaceRequest.serialize, + response_deserializer=namespace.Namespace.deserialize, + ) + return self._stubs['get_namespace'] + + @property + def update_namespace(self) -> Callable[ + [registration_service.UpdateNamespaceRequest], + Awaitable[gcs_namespace.Namespace]]: + r"""Return a callable for the update namespace method over gRPC. + + Updates a namespace. + + Returns: + Callable[[~.UpdateNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['update_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/UpdateNamespace', + request_serializer=registration_service.UpdateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs['update_namespace'] + + @property + def delete_namespace(self) -> Callable[ + [registration_service.DeleteNamespaceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete namespace method over gRPC. + + Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Returns: + Callable[[~.DeleteNamespaceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_namespace' not in self._stubs: + self._stubs['delete_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/DeleteNamespace', + request_serializer=registration_service.DeleteNamespaceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_namespace'] + + @property + def create_service(self) -> Callable[ + [registration_service.CreateServiceRequest], + Awaitable[gcs_service.Service]]: + r"""Return a callable for the create service method over gRPC. + + Creates a service, and returns the new Service. + + Returns: + Callable[[~.CreateServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/CreateService', + request_serializer=registration_service.CreateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs['create_service'] + + @property + def list_services(self) -> Callable[ + [registration_service.ListServicesRequest], + Awaitable[registration_service.ListServicesResponse]]: + r"""Return a callable for the list services method over gRPC. + + Lists all services belonging to a namespace. + + Returns: + Callable[[~.ListServicesRequest], + Awaitable[~.ListServicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/ListServices', + request_serializer=registration_service.ListServicesRequest.serialize, + response_deserializer=registration_service.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [registration_service.GetServiceRequest], + Awaitable[service.Service]]: + r"""Return a callable for the get service method over gRPC. + + Gets a service. + + Returns: + Callable[[~.GetServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/GetService', + request_serializer=registration_service.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def update_service(self) -> Callable[ + [registration_service.UpdateServiceRequest], + Awaitable[gcs_service.Service]]: + r"""Return a callable for the update service method over gRPC. + + Updates a service. + + Returns: + Callable[[~.UpdateServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/UpdateService', + request_serializer=registration_service.UpdateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [registration_service.DeleteServiceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a service. This also deletes all endpoints + associated with the service. + + Returns: + Callable[[~.DeleteServiceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/DeleteService', + request_serializer=registration_service.DeleteServiceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_service'] + + @property + def create_endpoint(self) -> Callable[ + [registration_service.CreateEndpointRequest], + Awaitable[gcs_endpoint.Endpoint]]: + r"""Return a callable for the create endpoint method over gRPC. + + Creates a endpoint, and returns the new Endpoint. + + Returns: + Callable[[~.CreateEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['create_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/CreateEndpoint', + request_serializer=registration_service.CreateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs['create_endpoint'] + + @property + def list_endpoints(self) -> Callable[ + [registration_service.ListEndpointsRequest], + Awaitable[registration_service.ListEndpointsResponse]]: + r"""Return a callable for the list endpoints method over gRPC. + + Lists all endpoints. + + Returns: + Callable[[~.ListEndpointsRequest], + Awaitable[~.ListEndpointsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoints' not in self._stubs: + self._stubs['list_endpoints'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/ListEndpoints', + request_serializer=registration_service.ListEndpointsRequest.serialize, + response_deserializer=registration_service.ListEndpointsResponse.deserialize, + ) + return self._stubs['list_endpoints'] + + @property + def get_endpoint(self) -> Callable[ + [registration_service.GetEndpointRequest], + Awaitable[endpoint.Endpoint]]: + r"""Return a callable for the get endpoint method over gRPC. + + Gets a endpoint. + + Returns: + Callable[[~.GetEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['get_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/GetEndpoint', + request_serializer=registration_service.GetEndpointRequest.serialize, + response_deserializer=endpoint.Endpoint.deserialize, + ) + return self._stubs['get_endpoint'] + + @property + def update_endpoint(self) -> Callable[ + [registration_service.UpdateEndpointRequest], + Awaitable[gcs_endpoint.Endpoint]]: + r"""Return a callable for the update endpoint method over gRPC. + + Updates a endpoint. + + Returns: + Callable[[~.UpdateEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['update_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/UpdateEndpoint', + request_serializer=registration_service.UpdateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs['update_endpoint'] + + @property + def delete_endpoint(self) -> Callable[ + [registration_service.DeleteEndpointRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete endpoint method over gRPC. + + Deletes a endpoint. + + Returns: + Callable[[~.DeleteEndpointRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_endpoint' not in self._stubs: + self._stubs['delete_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1.RegistrationService/DeleteEndpoint', + request_serializer=registration_service.DeleteEndpointRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_endpoint'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM Policy for a resource (namespace or + service only). + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.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.cloud.servicedirectory.v1.RegistrationService/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM Policy for a resource (namespace or + service only). + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.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.cloud.servicedirectory.v1.RegistrationService/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests IAM permissions for a resource (namespace or + service only). + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.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.cloud.servicedirectory.v1.RegistrationService/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'RegistrationServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/__init__.py new file mode 100644 index 00000000..acf22489 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/__init__.py @@ -0,0 +1,74 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .endpoint import ( + Endpoint, +) +from .lookup_service import ( + ResolveServiceRequest, + ResolveServiceResponse, +) +from .namespace import ( + Namespace, +) +from .registration_service import ( + CreateEndpointRequest, + CreateNamespaceRequest, + CreateServiceRequest, + DeleteEndpointRequest, + DeleteNamespaceRequest, + DeleteServiceRequest, + GetEndpointRequest, + GetNamespaceRequest, + GetServiceRequest, + ListEndpointsRequest, + ListEndpointsResponse, + ListNamespacesRequest, + ListNamespacesResponse, + ListServicesRequest, + ListServicesResponse, + UpdateEndpointRequest, + UpdateNamespaceRequest, + UpdateServiceRequest, +) +from .service import ( + Service, +) + +__all__ = ( + 'Endpoint', + 'ResolveServiceRequest', + 'ResolveServiceResponse', + 'Namespace', + 'CreateEndpointRequest', + 'CreateNamespaceRequest', + 'CreateServiceRequest', + 'DeleteEndpointRequest', + 'DeleteNamespaceRequest', + 'DeleteServiceRequest', + 'GetEndpointRequest', + 'GetNamespaceRequest', + 'GetServiceRequest', + 'ListEndpointsRequest', + 'ListEndpointsResponse', + 'ListNamespacesRequest', + 'ListNamespacesResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'UpdateEndpointRequest', + 'UpdateNamespaceRequest', + 'UpdateServiceRequest', + 'Service', +) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/endpoint.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/endpoint.py new file mode 100644 index 00000000..20801a22 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/endpoint.py @@ -0,0 +1,90 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.servicedirectory.v1', + manifest={ + 'Endpoint', + }, +) + + +class Endpoint(proto.Message): + r"""An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. The service + must already exist to create an endpoint. + + Attributes: + name (str): + Immutable. The resource name for the endpoint in the format + 'projects/*/locations/*/namespaces/*/services/*/endpoints/*'. + address (str): + Optional. An IPv4 or IPv6 address. Service Directory will + reject bad addresses like: "8.8.8" "8.8.8.8:53" + "test:bad:address" "[::1]" "[::1]:8080" Limited to 45 + characters. + port (int): + Optional. Service Directory will reject values outside of + [0, 65535]. + annotations (Sequence[google.cloud.servicedirectory_v1.types.Endpoint.AnnotationsEntry]): + Optional. Annotations for the endpoint. This data can be + consumed by service clients. Restrictions: + + - The entire annotations dictionary may contain up to 512 + characters, spread accoss all key-value pairs. + Annotations that goes beyond any these limits will be + rejected. + - Valid annotation keys have two segments: an optional + prefix and name, separated by a slash (/). The name + segment is required and must be 63 characters or less, + beginning and ending with an alphanumeric character + ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), + and alphanumerics between. The prefix is optional. If + specified, the prefix must be a DNS subdomain: a series + of DNS labels separated by dots (.), not longer than 253 + characters in total, followed by a slash (/). Annotations + that fails to meet these requirements will be rejected. + - The '(*.)google.com/' and '(*.)googleapis.com/' prefixes + are reserved for system annotations managed by Service + Directory. If the user tries to write to these keyspaces, + those entries will be silently ignored by the system. + Note: This field is equivalent to the 'metadata' field in + the v1beta1 API. They have the same syntax and read/write + to the same location in Service Directory. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + address = proto.Field( + proto.STRING, + number=2, + ) + port = proto.Field( + proto.INT32, + number=3, + ) + annotations = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/lookup_service.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/lookup_service.py new file mode 100644 index 00000000..0f148f70 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/lookup_service.py @@ -0,0 +1,95 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.servicedirectory_v1.types import service as gcs_service + + +__protobuf__ = proto.module( + package='google.cloud.servicedirectory.v1', + manifest={ + 'ResolveServiceRequest', + 'ResolveServiceResponse', + }, +) + + +class ResolveServiceRequest(proto.Message): + r"""The request message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + Looks up a service by its name, returns the service and its + endpoints. + + Attributes: + name (str): + Required. The name of the service to resolve. + max_endpoints (int): + Optional. The maximum number of endpoints to + return. Defaults to 25. Maximum is 100. If a + value less than one is specified, the Default is + used. If a value greater than the Maximum is + specified, the Maximum is used. + endpoint_filter (str): + Optional. The filter applied to the endpoints of the + resolved service. + + General filter string syntax: () can be "name" or + "metadata." for map field. can be "<, >, <=, >=, !=, =, :". + Of which ":" means HAS and is roughly the same as "=". must + be the same data type as the field. can be "AND, OR, NOT". + + Examples of valid filters: + + - "metadata.owner" returns Endpoints that have a label with + the key "owner", this is the same as "metadata:owner" + - "metadata.protocol=gRPC" returns Endpoints that have + key/value "protocol=gRPC" + - "metadata.owner!=sd AND metadata.foo=bar" returns + Endpoints that have "owner" field in metadata with a + value that is not "sd" AND have the key/value foo=bar. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + max_endpoints = proto.Field( + proto.INT32, + number=2, + ) + endpoint_filter = proto.Field( + proto.STRING, + number=3, + ) + + +class ResolveServiceResponse(proto.Message): + r"""The response message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + + Attributes: + service (google.cloud.servicedirectory_v1.types.Service): + + """ + + service = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_service.Service, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/namespace.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/namespace.py new file mode 100644 index 00000000..f6c0fb5a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/namespace.py @@ -0,0 +1,55 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.servicedirectory.v1', + manifest={ + 'Namespace', + }, +) + + +class Namespace(proto.Message): + r"""A container for + [services][google.cloud.servicedirectory.v1.Service]. Namespaces + allow administrators to group services together and define + permissions for a collection of services. + + Attributes: + name (str): + Immutable. The resource name for the namespace in the format + 'projects/*/locations/*/namespaces/*'. + labels (Sequence[google.cloud.servicedirectory_v1.types.Namespace.LabelsEntry]): + Optional. Resource labels associated with + this Namespace. No more than 64 user labels can + be associated with a given resource. Label keys + and values can be no longer than 63 characters. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/registration_service.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/registration_service.py new file mode 100644 index 00000000..76d1511f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/registration_service.py @@ -0,0 +1,614 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.servicedirectory.v1', + manifest={ + 'CreateNamespaceRequest', + 'ListNamespacesRequest', + 'ListNamespacesResponse', + 'GetNamespaceRequest', + 'UpdateNamespaceRequest', + 'DeleteNamespaceRequest', + 'CreateServiceRequest', + 'ListServicesRequest', + 'ListServicesResponse', + 'GetServiceRequest', + 'UpdateServiceRequest', + 'DeleteServiceRequest', + 'CreateEndpointRequest', + 'ListEndpointsRequest', + 'ListEndpointsResponse', + 'GetEndpointRequest', + 'UpdateEndpointRequest', + 'DeleteEndpointRequest', + }, +) + + +class CreateNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1.RegistrationService.CreateNamespace]. + + Attributes: + parent (str): + Required. The resource name of the project + and location the namespace will be created in. + namespace_id (str): + Required. The Resource ID must be 1-63 characters long, and + comply with RFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + namespace (google.cloud.servicedirectory_v1.types.Namespace): + Required. A namespace with initial fields + set. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + namespace_id = proto.Field( + proto.STRING, + number=2, + ) + namespace = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_namespace.Namespace, + ) + + +class ListNamespacesRequest(proto.Message): + r"""The request message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + + Attributes: + parent (str): + Required. The resource name of the project + and location whose namespaces we'd like to list. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to list result by. + + General filter string syntax: () can be "name", or "labels." + for map field. can be "<, >, <=, >=, !=, =, :". Of which ":" + means HAS, and is roughly the same as "=". must be the same + data type as field. can be "AND, OR, NOT". + + Examples of valid filters: + + - "labels.owner" returns Namespaces that have a label with + the key "owner" this is the same as "labels:owner". + - "labels.protocol=gRPC" returns Namespaces that have + key/value "protocol=gRPC". + - "name>projects/my-project/locations/us-east/namespaces/namespace-c" + returns Namespaces that have name that is alphabetically + later than the string, so "namespace-e" will be returned + but "namespace-a" will not be. + - "labels.owner!=sd AND labels.foo=bar" returns Namespaces + that have "owner" in label key but value is not "sd" AND + have key/value foo=bar. + - "doesnotexist.foo=bar" returns an empty list. Note that + Namespace doesn't have a field called "doesnotexist". + Since the filter does not match any Namespaces, it + returns no results. + order_by (str): + Optional. The order to list result by. + + General order by string syntax: () (,) allows + values {"name"} ascending or descending order by + . If this is left blank, "asc" is used. Note that an empty + order_by string result in default order, which is order by + name in ascending order. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class ListNamespacesResponse(proto.Message): + r"""The response message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + + Attributes: + namespaces (Sequence[google.cloud.servicedirectory_v1.types.Namespace]): + The list of namespaces. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + namespaces = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_namespace.Namespace, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1.RegistrationService.GetNamespace]. + + Attributes: + name (str): + Required. The name of the namespace to + retrieve. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1.RegistrationService.UpdateNamespace]. + + Attributes: + namespace (google.cloud.servicedirectory_v1.types.Namespace): + Required. The updated namespace. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + namespace = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_namespace.Namespace, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1.RegistrationService.DeleteNamespace]. + + Attributes: + name (str): + Required. The name of the namespace to + delete. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.CreateService][google.cloud.servicedirectory.v1.RegistrationService.CreateService]. + + Attributes: + parent (str): + Required. The resource name of the namespace + this service will belong to. + service_id (str): + Required. The Resource ID must be 1-63 characters long, and + comply with RFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + service (google.cloud.servicedirectory_v1.types.Service): + Required. A service with initial fields set. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + service_id = proto.Field( + proto.STRING, + number=2, + ) + service = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_service.Service, + ) + + +class ListServicesRequest(proto.Message): + r"""The request message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + + Attributes: + parent (str): + Required. The resource name of the namespace + whose services we'd like to list. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to list result by. + + General filter string syntax: () can be "name", or + "metadata." for map field. can be "<, >, <=, >=, !=, =, :". + Of which ":" means HAS, and is roughly the same as "=". must + be the same data type as field. can be "AND, OR, NOT". + + Examples of valid filters: + + - "metadata.owner" returns Services that have a label with + the key "owner" this is the same as "metadata:owner". + - "metadata.protocol=gRPC" returns Services that have + key/value "protocol=gRPC". + - "name>projects/my-project/locations/us-east/namespaces/my-namespace/services/service-c" + returns Services that have name that is alphabetically + later than the string, so "service-e" will be returned + but "service-a" will not be. + - "metadata.owner!=sd AND metadata.foo=bar" returns + Services that have "owner" in label key but value is not + "sd" AND have key/value foo=bar. + - "doesnotexist.foo=bar" returns an empty list. Note that + Service doesn't have a field called "doesnotexist". Since + the filter does not match any Services, it returns no + results. + order_by (str): + Optional. The order to list result by. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class ListServicesResponse(proto.Message): + r"""The response message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + + Attributes: + services (Sequence[google.cloud.servicedirectory_v1.types.Service]): + The list of services. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + services = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_service.Service, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.GetService][google.cloud.servicedirectory.v1.RegistrationService.GetService]. + This should not be used for looking up a service. Insead, use the + ``resolve`` method as it will contain all endpoints and associated + metadata. + + Attributes: + name (str): + Required. The name of the service to get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.UpdateService][google.cloud.servicedirectory.v1.RegistrationService.UpdateService]. + + Attributes: + service (google.cloud.servicedirectory_v1.types.Service): + Required. The updated service. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + service = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_service.Service, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.DeleteService][google.cloud.servicedirectory.v1.RegistrationService.DeleteService]. + + Attributes: + name (str): + Required. The name of the service to delete. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.CreateEndpoint]. + + Attributes: + parent (str): + Required. The resource name of the service + that this endpoint provides. + endpoint_id (str): + Required. The Resource ID must be 1-63 characters long, and + comply with RFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + endpoint (google.cloud.servicedirectory_v1.types.Endpoint): + Required. A endpoint with initial fields set. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + endpoint_id = proto.Field( + proto.STRING, + number=2, + ) + endpoint = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_endpoint.Endpoint, + ) + + +class ListEndpointsRequest(proto.Message): + r"""The request message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + + Attributes: + parent (str): + Required. The resource name of the service + whose endpoints we'd like to list. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to list result by. + + General filter string syntax: () can be "name", "address", + "port" or "metadata." for map field. can be "<, >, <=, >=, + !=, =, :". Of which ":" means HAS, and is roughly the same + as "=". must be the same data type as field. can be "AND, + OR, NOT". + + Examples of valid filters: + + - "metadata.owner" returns Endpoints that have a label with + the key "owner" this is the same as "metadata:owner". + - "metadata.protocol=gRPC" returns Endpoints that have + key/value "protocol=gRPC". + - "address=192.108.1.105" returns Endpoints that have this + address. + - "port>8080" returns Endpoints that have port number + larger than 8080. + - "name>projects/my-project/locations/us-east/namespaces/my-namespace/services/my-service/endpoints/endpoint-c" + returns Endpoints that have name that is alphabetically + later than the string, so "endpoint-e" will be returned + but "endpoint-a" will not be. + - "metadata.owner!=sd AND metadata.foo=bar" returns + Endpoints that have "owner" in label key but value is not + "sd" AND have key/value foo=bar. + - "doesnotexist.foo=bar" returns an empty list. Note that + Endpoint doesn't have a field called "doesnotexist". + Since the filter does not match any Endpoints, it returns + no results. + order_by (str): + Optional. The order to list result by. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEndpointsResponse(proto.Message): + r"""The response message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + + Attributes: + endpoints (Sequence[google.cloud.servicedirectory_v1.types.Endpoint]): + The list of endpoints. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + endpoints = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_endpoint.Endpoint, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1.RegistrationService.GetEndpoint]. + This should not be used to lookup endpoints at runtime. Instead, use + the ``resolve`` method. + + Attributes: + name (str): + Required. The name of the endpoint to get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.UpdateEndpoint]. + + Attributes: + endpoint (google.cloud.servicedirectory_v1.types.Endpoint): + Required. The updated endpoint. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + endpoint = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_endpoint.Endpoint, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1.RegistrationService.DeleteEndpoint]. + + Attributes: + name (str): + Required. The name of the endpoint to delete. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/service.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/service.py new file mode 100644 index 00000000..ddbb594a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/service.py @@ -0,0 +1,87 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.servicedirectory_v1.types import endpoint + + +__protobuf__ = proto.module( + package='google.cloud.servicedirectory.v1', + manifest={ + 'Service', + }, +) + + +class Service(proto.Message): + r"""An individual service. A service contains a name and optional + metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] can be added + to it. + + Attributes: + name (str): + Immutable. The resource name for the service in the format + 'projects/*/locations/*/namespaces/*/services/*'. + annotations (Sequence[google.cloud.servicedirectory_v1.types.Service.AnnotationsEntry]): + Optional. Annotations for the service. This data can be + consumed by service clients. Restrictions: + + - The entire annotations dictionary may contain up to 2000 + characters, spread accoss all key-value pairs. + Annotations that goes beyond any these limits will be + rejected. + - Valid annotation keys have two segments: an optional + prefix and name, separated by a slash (/). The name + segment is required and must be 63 characters or less, + beginning and ending with an alphanumeric character + ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), + and alphanumerics between. The prefix is optional. If + specified, the prefix must be a DNS subdomain: a series + of DNS labels separated by dots (.), not longer than 253 + characters in total, followed by a slash (/). Annotations + that fails to meet these requirements will be rejected. + - The '(*.)google.com/' and '(*.)googleapis.com/' prefixes + are reserved for system annotations managed by Service + Directory. If the user tries to write to these keyspaces, + those entries will be silently ignored by the system. + Note: This field is equivalent to the 'metadata' field in + the v1beta1 API. They have the same syntax and read/write + to the same location in Service Directory. + endpoints (Sequence[google.cloud.servicedirectory_v1.types.Endpoint]): + Output only. Endpoints associated with this + service. Returned on LookupService.Resolve. + Control plane clients should use + RegistrationService.ListEndpoints. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + annotations = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + endpoints = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=endpoint.Endpoint, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 00000000..7706e4bc --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,132 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/servicedirectory_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + '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='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1/scripts/fixup_servicedirectory_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_servicedirectory_v1_keywords.py new file mode 100644 index 00000000..892e98cf --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_servicedirectory_v1_keywords.py @@ -0,0 +1,194 @@ +#! /usr/bin/env python3 +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 servicedirectoryCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_endpoint': ('parent', 'endpoint_id', 'endpoint', ), + 'create_namespace': ('parent', 'namespace_id', 'namespace', ), + 'create_service': ('parent', 'service_id', 'service', ), + 'delete_endpoint': ('name', ), + 'delete_namespace': ('name', ), + 'delete_service': ('name', ), + 'get_endpoint': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_namespace': ('name', ), + 'get_service': ('name', ), + 'list_endpoints': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_namespaces': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_services': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'resolve_service': ('name', 'max_endpoints', 'endpoint_filter', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_endpoint': ('endpoint', 'update_mask', ), + 'update_namespace': ('namespace', 'update_mask', ), + 'update_service': ('service', 'update_mask', ), + } + + 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=servicedirectoryCallTransformer(), +): + """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 servicedirectory 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/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 00000000..f503a7fb --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,54 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 setuptools # type: ignore + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-servicedirectory', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1/tests/unit/gapic/servicedirectory_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py b/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py new file mode 100644 index 00000000..64c9100b --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py @@ -0,0 +1,1157 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +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 path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicedirectory_v1.services.lookup_service import LookupServiceAsyncClient +from google.cloud.servicedirectory_v1.services.lookup_service import LookupServiceClient +from google.cloud.servicedirectory_v1.services.lookup_service import transports +from google.cloud.servicedirectory_v1.services.lookup_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.servicedirectory_v1.types import lookup_service +from google.cloud.servicedirectory_v1.types import service +from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert LookupServiceClient._get_default_mtls_endpoint(None) is None + assert LookupServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LookupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LookupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LookupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LookupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + LookupServiceClient, + LookupServiceAsyncClient, +]) +def test_lookup_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.LookupServiceGrpcTransport, "grpc"), + (transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_lookup_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", [ + LookupServiceClient, + LookupServiceAsyncClient, +]) +def test_lookup_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +def test_lookup_service_client_get_transport_class(): + transport = LookupServiceClient.get_transport_class() + available_transports = [ + transports.LookupServiceGrpcTransport, + ] + assert transport in available_transports + + transport = LookupServiceClient.get_transport_class("grpc") + assert transport == transports.LookupServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(LookupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceClient)) +@mock.patch.object(LookupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceAsyncClient)) +def test_lookup_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(LookupServiceClient, '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(LookupServiceClient, '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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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() + 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "true"), + (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "false"), + (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(LookupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceClient)) +@mock.patch.object(LookupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_lookup_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_lookup_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_lookup_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_lookup_service_client_client_options_from_dict(): + with mock.patch('google.cloud.servicedirectory_v1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LookupServiceClient( + 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, + ) + + +def test_resolve_service(transport: str = 'grpc', request_type=lookup_service.ResolveServiceRequest): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lookup_service.ResolveServiceResponse( + ) + response = client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == lookup_service.ResolveServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, lookup_service.ResolveServiceResponse) + + +def test_resolve_service_from_dict(): + test_resolve_service(request_type=dict) + + +def test_resolve_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_service), + '__call__') as call: + client.resolve_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lookup_service.ResolveServiceRequest() + + +@pytest.mark.asyncio +async def test_resolve_service_async(transport: str = 'grpc_asyncio', request_type=lookup_service.ResolveServiceRequest): + client = LookupServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lookup_service.ResolveServiceResponse( + )) + response = await client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == lookup_service.ResolveServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, lookup_service.ResolveServiceResponse) + + +@pytest.mark.asyncio +async def test_resolve_service_async_from_dict(): + await test_resolve_service_async(request_type=dict) + + +def test_resolve_service_field_headers(): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lookup_service.ResolveServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_service), + '__call__') as call: + call.return_value = lookup_service.ResolveServiceResponse() + client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_resolve_service_field_headers_async(): + client = LookupServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lookup_service.ResolveServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lookup_service.ResolveServiceResponse()) + await client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LookupServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LookupServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, +]) +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_grpc_default(): + # A client should use the gRPC transport by default. + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LookupServiceGrpcTransport, + ) + +def test_lookup_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LookupServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_lookup_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LookupServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'resolve_service', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +@requires_google_auth_gte_1_25_0 +def test_lookup_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.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LookupServiceTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_lookup_service_base_transport_with_credentials_file_old_google_auth(): + # 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.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LookupServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_lookup_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.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LookupServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_lookup_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) + LookupServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_lookup_service_auth_adc_old_google_auth(): + # 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) + LookupServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_lookup_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.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_lookup_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LookupServiceGrpcTransport, grpc_helpers), + (transports.LookupServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_lookup_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( + "servicedirectory.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="servicedirectory.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) +def test_lookup_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_lookup_service_host_no_port(): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com'), + ) + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +def test_lookup_service_host_with_port(): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com:8000'), + ) + assert client.transport._host == 'servicedirectory.googleapis.com:8000' + +def test_lookup_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LookupServiceGrpcTransport( + 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_lookup_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LookupServiceGrpcAsyncIOTransport( + 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.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) +def test_lookup_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.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) +def test_lookup_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_endpoint_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + endpoint = "oyster" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) + actual = LookupServiceClient.endpoint_path(project, location, namespace, service, endpoint) + assert expected == actual + + +def test_parse_endpoint_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "namespace": "mussel", + "service": "winkle", + "endpoint": "nautilus", + } + path = LookupServiceClient.endpoint_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_endpoint_path(path) + assert expected == actual + +def test_service_path(): + project = "scallop" + location = "abalone" + namespace = "squid" + service = "clam" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + actual = LookupServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "whelk", + "location": "octopus", + "namespace": "oyster", + "service": "nudibranch", + } + path = LookupServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LookupServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = LookupServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = LookupServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = LookupServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LookupServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = LookupServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = LookupServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = LookupServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = LookupServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = LookupServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.LookupServiceTransport, '_prep_wrapped_messages') as prep: + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LookupServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = LookupServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = LookupServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = LookupServiceClient( + 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() diff --git a/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_registration_service.py b/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_registration_service.py new file mode 100644 index 00000000..5ae52c56 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_registration_service.py @@ -0,0 +1,5654 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +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 path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicedirectory_v1.services.registration_service import RegistrationServiceAsyncClient +from google.cloud.servicedirectory_v1.services.registration_service import RegistrationServiceClient +from google.cloud.servicedirectory_v1.services.registration_service import pagers +from google.cloud.servicedirectory_v1.services.registration_service import transports +from google.cloud.servicedirectory_v1.services.registration_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +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.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RegistrationServiceClient._get_default_mtls_endpoint(None) is None + assert RegistrationServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RegistrationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RegistrationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RegistrationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RegistrationServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + RegistrationServiceClient, + RegistrationServiceAsyncClient, +]) +def test_registration_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RegistrationServiceGrpcTransport, "grpc"), + (transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_registration_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", [ + RegistrationServiceClient, + RegistrationServiceAsyncClient, +]) +def test_registration_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +def test_registration_service_client_get_transport_class(): + transport = RegistrationServiceClient.get_transport_class() + available_transports = [ + transports.RegistrationServiceGrpcTransport, + ] + assert transport in available_transports + + transport = RegistrationServiceClient.get_transport_class("grpc") + assert transport == transports.RegistrationServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), + (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(RegistrationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceClient)) +@mock.patch.object(RegistrationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceAsyncClient)) +def test_registration_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(RegistrationServiceClient, '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(RegistrationServiceClient, '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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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() + 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc", "true"), + (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc", "false"), + (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(RegistrationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceClient)) +@mock.patch.object(RegistrationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_registration_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), + (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_registration_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), + (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_registration_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_registration_service_client_client_options_from_dict(): + with mock.patch('google.cloud.servicedirectory_v1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RegistrationServiceClient( + 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, + ) + + +def test_create_namespace(transport: str = 'grpc', request_type=registration_service.CreateNamespaceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace( + name='name_value', + ) + response = client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + assert response.name == 'name_value' + + +def test_create_namespace_from_dict(): + test_create_namespace(request_type=dict) + + +def test_create_namespace_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_namespace), + '__call__') as call: + client.create_namespace() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateNamespaceRequest() + + +@pytest.mark.asyncio +async def test_create_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateNamespaceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace( + name='name_value', + )) + response = await client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_namespace_async_from_dict(): + await test_create_namespace_async(request_type=dict) + + +def test_create_namespace_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateNamespaceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_namespace), + '__call__') as call: + call.return_value = gcs_namespace.Namespace() + client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateNamespaceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_namespace), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) + await client.create_namespace(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_namespace_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_namespace( + parent='parent_value', + namespace=gcs_namespace.Namespace(name='name_value'), + namespace_id='namespace_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].namespace == gcs_namespace.Namespace(name='name_value') + assert args[0].namespace_id == 'namespace_id_value' + + +def test_create_namespace_flattened_error(): + client = RegistrationServiceClient( + 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_namespace( + registration_service.CreateNamespaceRequest(), + parent='parent_value', + namespace=gcs_namespace.Namespace(name='name_value'), + namespace_id='namespace_id_value', + ) + + +@pytest.mark.asyncio +async def test_create_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_namespace( + parent='parent_value', + namespace=gcs_namespace.Namespace(name='name_value'), + namespace_id='namespace_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].namespace == gcs_namespace.Namespace(name='name_value') + assert args[0].namespace_id == 'namespace_id_value' + + +@pytest.mark.asyncio +async def test_create_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_namespace( + registration_service.CreateNamespaceRequest(), + parent='parent_value', + namespace=gcs_namespace.Namespace(name='name_value'), + namespace_id='namespace_id_value', + ) + + +def test_list_namespaces(transport: str = 'grpc', request_type=registration_service.ListNamespacesRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListNamespacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNamespacesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_namespaces_from_dict(): + test_list_namespaces(request_type=dict) + + +def test_list_namespaces_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + client.list_namespaces() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListNamespacesRequest() + + +@pytest.mark.asyncio +async def test_list_namespaces_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListNamespacesRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListNamespacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNamespacesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_namespaces_async_from_dict(): + await test_list_namespaces_async(request_type=dict) + + +def test_list_namespaces_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListNamespacesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + call.return_value = registration_service.ListNamespacesResponse() + client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_namespaces_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListNamespacesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse()) + await client.list_namespaces(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_namespaces_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_namespaces( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_namespaces_flattened_error(): + client = RegistrationServiceClient( + 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_namespaces( + registration_service.ListNamespacesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_namespaces_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_namespaces( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_namespaces_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_namespaces( + registration_service.ListNamespacesRequest(), + parent='parent_value', + ) + + +def test_list_namespaces_pager(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token='abc', + ), + registration_service.ListNamespacesResponse( + namespaces=[], + next_page_token='def', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + ], + next_page_token='ghi', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_namespaces(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, namespace.Namespace) + for i in results) + +def test_list_namespaces_pages(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token='abc', + ), + registration_service.ListNamespacesResponse( + namespaces=[], + next_page_token='def', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + ], + next_page_token='ghi', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + ], + ), + RuntimeError, + ) + pages = list(client.list_namespaces(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_namespaces_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token='abc', + ), + registration_service.ListNamespacesResponse( + namespaces=[], + next_page_token='def', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + ], + next_page_token='ghi', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_namespaces(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, namespace.Namespace) + for i in responses) + +@pytest.mark.asyncio +async def test_list_namespaces_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token='abc', + ), + registration_service.ListNamespacesResponse( + namespaces=[], + next_page_token='def', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + ], + next_page_token='ghi', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_namespaces(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_namespace(transport: str = 'grpc', request_type=registration_service.GetNamespaceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace( + name='name_value', + ) + response = client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, namespace.Namespace) + assert response.name == 'name_value' + + +def test_get_namespace_from_dict(): + test_get_namespace(request_type=dict) + + +def test_get_namespace_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_namespace), + '__call__') as call: + client.get_namespace() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetNamespaceRequest() + + +@pytest.mark.asyncio +async def test_get_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetNamespaceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace( + name='name_value', + )) + response = await client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, namespace.Namespace) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_namespace_async_from_dict(): + await test_get_namespace_async(request_type=dict) + + +def test_get_namespace_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetNamespaceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_namespace), + '__call__') as call: + call.return_value = namespace.Namespace() + client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetNamespaceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_namespace), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) + await client.get_namespace(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_namespace_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_namespace( + 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] + assert args[0].name == 'name_value' + + +def test_get_namespace_flattened_error(): + client = RegistrationServiceClient( + 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_namespace( + registration_service.GetNamespaceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_namespace( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_namespace( + registration_service.GetNamespaceRequest(), + name='name_value', + ) + + +def test_update_namespace(transport: str = 'grpc', request_type=registration_service.UpdateNamespaceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace( + name='name_value', + ) + response = client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + assert response.name == 'name_value' + + +def test_update_namespace_from_dict(): + test_update_namespace(request_type=dict) + + +def test_update_namespace_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_namespace), + '__call__') as call: + client.update_namespace() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateNamespaceRequest() + + +@pytest.mark.asyncio +async def test_update_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateNamespaceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace( + name='name_value', + )) + response = await client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_namespace_async_from_dict(): + await test_update_namespace_async(request_type=dict) + + +def test_update_namespace_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateNamespaceRequest() + + request.namespace.name = 'namespace.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_namespace), + '__call__') as call: + call.return_value = gcs_namespace.Namespace() + client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'namespace.name=namespace.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateNamespaceRequest() + + request.namespace.name = 'namespace.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_namespace), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) + await client.update_namespace(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', + 'namespace.name=namespace.name/value', + ) in kw['metadata'] + + +def test_update_namespace_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_namespace( + namespace=gcs_namespace.Namespace(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].namespace == gcs_namespace.Namespace(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_namespace_flattened_error(): + client = RegistrationServiceClient( + 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_namespace( + registration_service.UpdateNamespaceRequest(), + namespace=gcs_namespace.Namespace(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_namespace( + namespace=gcs_namespace.Namespace(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].namespace == gcs_namespace.Namespace(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_namespace( + registration_service.UpdateNamespaceRequest(), + namespace=gcs_namespace.Namespace(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_namespace(transport: str = 'grpc', request_type=registration_service.DeleteNamespaceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteNamespaceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_namespace_from_dict(): + test_delete_namespace(request_type=dict) + + +def test_delete_namespace_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_namespace), + '__call__') as call: + client.delete_namespace() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteNamespaceRequest() + + +@pytest.mark.asyncio +async def test_delete_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteNamespaceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteNamespaceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_namespace_async_from_dict(): + await test_delete_namespace_async(request_type=dict) + + +def test_delete_namespace_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteNamespaceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_namespace), + '__call__') as call: + call.return_value = None + client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteNamespaceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_namespace), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_namespace(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_namespace_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_namespace( + 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] + assert args[0].name == 'name_value' + + +def test_delete_namespace_flattened_error(): + client = RegistrationServiceClient( + 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_namespace( + registration_service.DeleteNamespaceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_namespace( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_namespace( + registration_service.DeleteNamespaceRequest(), + name='name_value', + ) + + +def test_create_service(transport: str = 'grpc', request_type=registration_service.CreateServiceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service( + name='name_value', + ) + response = client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + assert response.name == 'name_value' + + +def test_create_service_from_dict(): + test_create_service(request_type=dict) + + +def test_create_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + client.create_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateServiceRequest() + + +@pytest.mark.asyncio +async def test_create_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateServiceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service( + name='name_value', + )) + response = await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_service_async_from_dict(): + await test_create_service_async(request_type=dict) + + +def test_create_service_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateServiceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + call.return_value = gcs_service.Service() + client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateServiceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_create_service_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_service( + parent='parent_value', + service=gcs_service.Service(name='name_value'), + service_id='service_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].service == gcs_service.Service(name='name_value') + assert args[0].service_id == 'service_id_value' + + +def test_create_service_flattened_error(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_service( + registration_service.CreateServiceRequest(), + parent='parent_value', + service=gcs_service.Service(name='name_value'), + service_id='service_id_value', + ) + + +@pytest.mark.asyncio +async def test_create_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_service( + parent='parent_value', + service=gcs_service.Service(name='name_value'), + service_id='service_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].service == gcs_service.Service(name='name_value') + assert args[0].service_id == 'service_id_value' + + +@pytest.mark.asyncio +async def test_create_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_service( + registration_service.CreateServiceRequest(), + parent='parent_value', + service=gcs_service.Service(name='name_value'), + service_id='service_id_value', + ) + + +def test_list_services(transport: str = 'grpc', request_type=registration_service.ListServicesRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListServicesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_services_from_dict(): + test_list_services(request_type=dict) + + +def test_list_services_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + client.list_services() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListServicesRequest() + + +@pytest.mark.asyncio +async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListServicesRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_services_async_from_dict(): + await test_list_services_async(request_type=dict) + + +def test_list_services_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListServicesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = registration_service.ListServicesResponse() + client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_services_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListServicesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse()) + await client.list_services(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_services_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListServicesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_services( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_services_flattened_error(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_services( + registration_service.ListServicesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_services_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListServicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_services( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_services_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_services( + registration_service.ListServicesRequest(), + parent='parent_value', + ) + + +def test_list_services_pager(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + registration_service.ListServicesResponse( + services=[], + next_page_token='def', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_services(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, service.Service) + for i in results) + +def test_list_services_pages(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + registration_service.ListServicesResponse( + services=[], + next_page_token='def', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + pages = list(client.list_services(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_services_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + registration_service.ListServicesResponse( + services=[], + next_page_token='def', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_services(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, service.Service) + for i in responses) + +@pytest.mark.asyncio +async def test_list_services_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + registration_service.ListServicesResponse( + services=[], + next_page_token='def', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_services(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_service(transport: str = 'grpc', request_type=registration_service.GetServiceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.Service( + name='name_value', + ) + response = client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + assert response.name == 'name_value' + + +def test_get_service_from_dict(): + test_get_service(request_type=dict) + + +def test_get_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + client.get_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetServiceRequest() + + +@pytest.mark.asyncio +async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetServiceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.Service( + name='name_value', + )) + response = await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_service_async_from_dict(): + await test_get_service_async(request_type=dict) + + +def test_get_service_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = service.Service() + client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) + await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_service_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.Service() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_service_flattened_error(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_service( + registration_service.GetServiceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_service( + registration_service.GetServiceRequest(), + name='name_value', + ) + + +def test_update_service(transport: str = 'grpc', request_type=registration_service.UpdateServiceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service( + name='name_value', + ) + response = client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + assert response.name == 'name_value' + + +def test_update_service_from_dict(): + test_update_service(request_type=dict) + + +def test_update_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + client.update_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateServiceRequest() + + +@pytest.mark.asyncio +async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateServiceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service( + name='name_value', + )) + response = await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_service_async_from_dict(): + await test_update_service_async(request_type=dict) + + +def test_update_service_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateServiceRequest() + + request.service.name = 'service.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = gcs_service.Service() + client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service.name=service.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateServiceRequest() + + request.service.name = 'service.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service.name=service.name/value', + ) in kw['metadata'] + + +def test_update_service_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_service( + service=gcs_service.Service(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].service == gcs_service.Service(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_service_flattened_error(): + client = RegistrationServiceClient( + 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_service( + registration_service.UpdateServiceRequest(), + service=gcs_service.Service(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_service( + service=gcs_service.Service(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].service == gcs_service.Service(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_service( + registration_service.UpdateServiceRequest(), + service=gcs_service.Service(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_service(transport: str = 'grpc', request_type=registration_service.DeleteServiceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_service_from_dict(): + test_delete_service(request_type=dict) + + +def test_delete_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + client.delete_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteServiceRequest() + + +@pytest.mark.asyncio +async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteServiceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_service_async_from_dict(): + await test_delete_service_async(request_type=dict) + + +def test_delete_service_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = None + client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_service_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_delete_service_flattened_error(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_service( + registration_service.DeleteServiceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_service( + registration_service.DeleteServiceRequest(), + name='name_value', + ) + + +def test_create_endpoint(transport: str = 'grpc', request_type=registration_service.CreateEndpointRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + ) + response = client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + + +def test_create_endpoint_from_dict(): + test_create_endpoint(request_type=dict) + + +def test_create_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint), + '__call__') as call: + client.create_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateEndpointRequest() + + +@pytest.mark.asyncio +async def test_create_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateEndpointRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + )) + response = await client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + + +@pytest.mark.asyncio +async def test_create_endpoint_async_from_dict(): + await test_create_endpoint_async(request_type=dict) + + +def test_create_endpoint_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateEndpointRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint), + '__call__') as call: + call.return_value = gcs_endpoint.Endpoint() + client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateEndpointRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) + await client.create_endpoint(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_endpoint_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_endpoint( + parent='parent_value', + endpoint=gcs_endpoint.Endpoint(name='name_value'), + endpoint_id='endpoint_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') + assert args[0].endpoint_id == 'endpoint_id_value' + + +def test_create_endpoint_flattened_error(): + client = RegistrationServiceClient( + 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_endpoint( + registration_service.CreateEndpointRequest(), + parent='parent_value', + endpoint=gcs_endpoint.Endpoint(name='name_value'), + endpoint_id='endpoint_id_value', + ) + + +@pytest.mark.asyncio +async def test_create_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_endpoint( + parent='parent_value', + endpoint=gcs_endpoint.Endpoint(name='name_value'), + endpoint_id='endpoint_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') + assert args[0].endpoint_id == 'endpoint_id_value' + + +@pytest.mark.asyncio +async def test_create_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_endpoint( + registration_service.CreateEndpointRequest(), + parent='parent_value', + endpoint=gcs_endpoint.Endpoint(name='name_value'), + endpoint_id='endpoint_id_value', + ) + + +def test_list_endpoints(transport: str = 'grpc', request_type=registration_service.ListEndpointsRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListEndpointsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_endpoints_from_dict(): + test_list_endpoints(request_type=dict) + + +def test_list_endpoints_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + client.list_endpoints() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListEndpointsRequest() + + +@pytest.mark.asyncio +async def test_list_endpoints_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListEndpointsRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListEndpointsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_endpoints_async_from_dict(): + await test_list_endpoints_async(request_type=dict) + + +def test_list_endpoints_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListEndpointsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + call.return_value = registration_service.ListEndpointsResponse() + client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_endpoints_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListEndpointsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse()) + await client.list_endpoints(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_endpoints_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_endpoints( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_endpoints_flattened_error(): + client = RegistrationServiceClient( + 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_endpoints( + registration_service.ListEndpointsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_endpoints_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_endpoints( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_endpoints_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_endpoints( + registration_service.ListEndpointsRequest(), + parent='parent_value', + ) + + +def test_list_endpoints_pager(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token='abc', + ), + registration_service.ListEndpointsResponse( + endpoints=[], + next_page_token='def', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + ], + next_page_token='ghi', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_endpoints(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, endpoint.Endpoint) + for i in results) + +def test_list_endpoints_pages(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token='abc', + ), + registration_service.ListEndpointsResponse( + endpoints=[], + next_page_token='def', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + ], + next_page_token='ghi', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + ), + RuntimeError, + ) + pages = list(client.list_endpoints(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_endpoints_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token='abc', + ), + registration_service.ListEndpointsResponse( + endpoints=[], + next_page_token='def', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + ], + next_page_token='ghi', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_endpoints(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, endpoint.Endpoint) + for i in responses) + +@pytest.mark.asyncio +async def test_list_endpoints_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token='abc', + ), + registration_service.ListEndpointsResponse( + endpoints=[], + next_page_token='def', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + ], + next_page_token='ghi', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_endpoints(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_endpoint(transport: str = 'grpc', request_type=registration_service.GetEndpointRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + ) + response = client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + + +def test_get_endpoint_from_dict(): + test_get_endpoint(request_type=dict) + + +def test_get_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint), + '__call__') as call: + client.get_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetEndpointRequest() + + +@pytest.mark.asyncio +async def test_get_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetEndpointRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + )) + response = await client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + + +@pytest.mark.asyncio +async def test_get_endpoint_async_from_dict(): + await test_get_endpoint_async(request_type=dict) + + +def test_get_endpoint_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetEndpointRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint), + '__call__') as call: + call.return_value = endpoint.Endpoint() + client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetEndpointRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) + await client.get_endpoint(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_endpoint_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_endpoint( + 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] + assert args[0].name == 'name_value' + + +def test_get_endpoint_flattened_error(): + client = RegistrationServiceClient( + 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_endpoint( + registration_service.GetEndpointRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_endpoint( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_endpoint( + registration_service.GetEndpointRequest(), + name='name_value', + ) + + +def test_update_endpoint(transport: str = 'grpc', request_type=registration_service.UpdateEndpointRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + ) + response = client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + + +def test_update_endpoint_from_dict(): + test_update_endpoint(request_type=dict) + + +def test_update_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint), + '__call__') as call: + client.update_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateEndpointRequest() + + +@pytest.mark.asyncio +async def test_update_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateEndpointRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + )) + response = await client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + + +@pytest.mark.asyncio +async def test_update_endpoint_async_from_dict(): + await test_update_endpoint_async(request_type=dict) + + +def test_update_endpoint_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateEndpointRequest() + + request.endpoint.name = 'endpoint.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint), + '__call__') as call: + call.return_value = gcs_endpoint.Endpoint() + client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'endpoint.name=endpoint.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateEndpointRequest() + + request.endpoint.name = 'endpoint.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) + await client.update_endpoint(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', + 'endpoint.name=endpoint.name/value', + ) in kw['metadata'] + + +def test_update_endpoint_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_endpoint( + endpoint=gcs_endpoint.Endpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_endpoint_flattened_error(): + client = RegistrationServiceClient( + 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_endpoint( + registration_service.UpdateEndpointRequest(), + endpoint=gcs_endpoint.Endpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_endpoint( + endpoint=gcs_endpoint.Endpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_endpoint( + registration_service.UpdateEndpointRequest(), + endpoint=gcs_endpoint.Endpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_endpoint(transport: str = 'grpc', request_type=registration_service.DeleteEndpointRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteEndpointRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_endpoint_from_dict(): + test_delete_endpoint(request_type=dict) + + +def test_delete_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint), + '__call__') as call: + client.delete_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteEndpointRequest() + + +@pytest.mark.asyncio +async def test_delete_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteEndpointRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteEndpointRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_endpoint_async_from_dict(): + await test_delete_endpoint_async(request_type=dict) + + +def test_delete_endpoint_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteEndpointRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint), + '__call__') as call: + call.return_value = None + client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteEndpointRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_endpoint(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_endpoint_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_endpoint( + 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] + assert args[0].name == 'name_value' + + +def test_delete_endpoint_flattened_error(): + client = RegistrationServiceClient( + 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_endpoint( + registration_service.DeleteEndpointRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_endpoint( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_endpoint( + registration_service.DeleteEndpointRequest(), + name='name_value', + ) + + +def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + test_get_iam_policy(request_type=dict) + + +def test_get_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = RegistrationServiceClient( + 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() + + +def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + test_set_iam_policy(request_type=dict) + + +def test_set_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = RegistrationServiceClient( + 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() + + +def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + test_test_iam_permissions(request_type=dict) + + +def test_test_iam_permissions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = RegistrationServiceClient( + 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() + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegistrationServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RegistrationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, +]) +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_grpc_default(): + # A client should use the gRPC transport by default. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RegistrationServiceGrpcTransport, + ) + +def test_registration_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegistrationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_registration_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RegistrationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_namespace', + 'list_namespaces', + 'get_namespace', + 'update_namespace', + 'delete_namespace', + 'create_service', + 'list_services', + 'get_service', + 'update_service', + 'delete_service', + 'create_endpoint', + 'list_endpoints', + 'get_endpoint', + 'update_endpoint', + 'delete_endpoint', + 'get_iam_policy', + 'set_iam_policy', + 'test_iam_permissions', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +@requires_google_auth_gte_1_25_0 +def test_registration_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.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegistrationServiceTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_registration_service_base_transport_with_credentials_file_old_google_auth(): + # 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.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegistrationServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_registration_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.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegistrationServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_registration_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) + RegistrationServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_registration_service_auth_adc_old_google_auth(): + # 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) + RegistrationServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_registration_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.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_registration_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RegistrationServiceGrpcTransport, grpc_helpers), + (transports.RegistrationServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_registration_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( + "servicedirectory.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="servicedirectory.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) +def test_registration_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_registration_service_host_no_port(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com'), + ) + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +def test_registration_service_host_with_port(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com:8000'), + ) + assert client.transport._host == 'servicedirectory.googleapis.com:8000' + +def test_registration_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegistrationServiceGrpcTransport( + 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_registration_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegistrationServiceGrpcAsyncIOTransport( + 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.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) +def test_registration_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.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) +def test_registration_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_endpoint_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + endpoint = "oyster" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) + actual = RegistrationServiceClient.endpoint_path(project, location, namespace, service, endpoint) + assert expected == actual + + +def test_parse_endpoint_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "namespace": "mussel", + "service": "winkle", + "endpoint": "nautilus", + } + path = RegistrationServiceClient.endpoint_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_endpoint_path(path) + assert expected == actual + +def test_namespace_path(): + project = "scallop" + location = "abalone" + namespace = "squid" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}".format(project=project, location=location, namespace=namespace, ) + actual = RegistrationServiceClient.namespace_path(project, location, namespace) + assert expected == actual + + +def test_parse_namespace_path(): + expected = { + "project": "clam", + "location": "whelk", + "namespace": "octopus", + } + path = RegistrationServiceClient.namespace_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_namespace_path(path) + assert expected == actual + +def test_service_path(): + project = "oyster" + location = "nudibranch" + namespace = "cuttlefish" + service = "mussel" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + actual = RegistrationServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "namespace": "scallop", + "service": "abalone", + } + path = RegistrationServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RegistrationServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RegistrationServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = RegistrationServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RegistrationServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RegistrationServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RegistrationServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = RegistrationServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RegistrationServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RegistrationServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RegistrationServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RegistrationServiceTransport, '_prep_wrapped_messages') as prep: + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RegistrationServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = RegistrationServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = RegistrationServiceClient( + 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() diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc new file mode 100644 index 00000000..078f9e0e --- /dev/null +++ b/owl-bot-staging/v1beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/servicedirectory/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in new file mode 100644 index 00000000..1d83357d --- /dev/null +++ b/owl-bot-staging/v1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/servicedirectory *.py +recursive-include google/cloud/servicedirectory_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst new file mode 100644 index 00000000..2a61473b --- /dev/null +++ b/owl-bot-staging/v1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Servicedirectory 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 Servicedirectory 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py new file mode 100644 index 00000000..c8721e6e --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-service-directory 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-service-directory" +copyright = u"2020, 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 = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-service-directory-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 = [ + ( + master_doc, + "google-cloud-service-directory.tex", + u"google-cloud-service-directory 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 = [ + ( + master_doc, + "google-cloud-service-directory", + u"Google Cloud Servicedirectory 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 = [ + ( + master_doc, + "google-cloud-service-directory", + u"google-cloud-service-directory Documentation", + author, + "google-cloud-service-directory", + "GAPIC library for Google Cloud Servicedirectory 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/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst new file mode 100644 index 00000000..3b2d48ec --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + servicedirectory_v1beta1/services + servicedirectory_v1beta1/types diff --git a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/lookup_service.rst b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/lookup_service.rst new file mode 100644 index 00000000..787d8964 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/lookup_service.rst @@ -0,0 +1,6 @@ +LookupService +------------------------------- + +.. automodule:: google.cloud.servicedirectory_v1beta1.services.lookup_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/registration_service.rst b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/registration_service.rst new file mode 100644 index 00000000..de5871e4 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/registration_service.rst @@ -0,0 +1,10 @@ +RegistrationService +------------------------------------- + +.. automodule:: google.cloud.servicedirectory_v1beta1.services.registration_service + :members: + :inherited-members: + +.. automodule:: google.cloud.servicedirectory_v1beta1.services.registration_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/services.rst new file mode 100644 index 00000000..359795b0 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/services.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Servicedirectory v1beta1 API +====================================================== +.. toctree:: + :maxdepth: 2 + + lookup_service + registration_service diff --git a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/types.rst new file mode 100644 index 00000000..1a2daef4 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Servicedirectory v1beta1 API +=================================================== + +.. automodule:: google.cloud.servicedirectory_v1beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory/__init__.py new file mode 100644 index 00000000..f6952a07 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory/__init__.py @@ -0,0 +1,73 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.servicedirectory_v1beta1.services.lookup_service.client import LookupServiceClient +from google.cloud.servicedirectory_v1beta1.services.lookup_service.async_client import LookupServiceAsyncClient +from google.cloud.servicedirectory_v1beta1.services.registration_service.client import RegistrationServiceClient +from google.cloud.servicedirectory_v1beta1.services.registration_service.async_client import RegistrationServiceAsyncClient + +from google.cloud.servicedirectory_v1beta1.types.endpoint import Endpoint +from google.cloud.servicedirectory_v1beta1.types.lookup_service import ResolveServiceRequest +from google.cloud.servicedirectory_v1beta1.types.lookup_service import ResolveServiceResponse +from google.cloud.servicedirectory_v1beta1.types.namespace import Namespace +from google.cloud.servicedirectory_v1beta1.types.registration_service import CreateEndpointRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import CreateNamespaceRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import CreateServiceRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import DeleteEndpointRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import DeleteNamespaceRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import DeleteServiceRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import GetEndpointRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import GetNamespaceRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import GetServiceRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import ListEndpointsRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import ListEndpointsResponse +from google.cloud.servicedirectory_v1beta1.types.registration_service import ListNamespacesRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import ListNamespacesResponse +from google.cloud.servicedirectory_v1beta1.types.registration_service import ListServicesRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import ListServicesResponse +from google.cloud.servicedirectory_v1beta1.types.registration_service import UpdateEndpointRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import UpdateNamespaceRequest +from google.cloud.servicedirectory_v1beta1.types.registration_service import UpdateServiceRequest +from google.cloud.servicedirectory_v1beta1.types.service import Service + +__all__ = ('LookupServiceClient', + 'LookupServiceAsyncClient', + 'RegistrationServiceClient', + 'RegistrationServiceAsyncClient', + 'Endpoint', + 'ResolveServiceRequest', + 'ResolveServiceResponse', + 'Namespace', + 'CreateEndpointRequest', + 'CreateNamespaceRequest', + 'CreateServiceRequest', + 'DeleteEndpointRequest', + 'DeleteNamespaceRequest', + 'DeleteServiceRequest', + 'GetEndpointRequest', + 'GetNamespaceRequest', + 'GetServiceRequest', + 'ListEndpointsRequest', + 'ListEndpointsResponse', + 'ListNamespacesRequest', + 'ListNamespacesResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'UpdateEndpointRequest', + 'UpdateNamespaceRequest', + 'UpdateServiceRequest', + 'Service', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory/py.typed b/owl-bot-staging/v1beta1/google/cloud/servicedirectory/py.typed new file mode 100644 index 00000000..8a62d150 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-service-directory package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/__init__.py new file mode 100644 index 00000000..9160262b --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/__init__.py @@ -0,0 +1,74 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .services.lookup_service import LookupServiceClient +from .services.lookup_service import LookupServiceAsyncClient +from .services.registration_service import RegistrationServiceClient +from .services.registration_service import RegistrationServiceAsyncClient + +from .types.endpoint import Endpoint +from .types.lookup_service import ResolveServiceRequest +from .types.lookup_service import ResolveServiceResponse +from .types.namespace import Namespace +from .types.registration_service import CreateEndpointRequest +from .types.registration_service import CreateNamespaceRequest +from .types.registration_service import CreateServiceRequest +from .types.registration_service import DeleteEndpointRequest +from .types.registration_service import DeleteNamespaceRequest +from .types.registration_service import DeleteServiceRequest +from .types.registration_service import GetEndpointRequest +from .types.registration_service import GetNamespaceRequest +from .types.registration_service import GetServiceRequest +from .types.registration_service import ListEndpointsRequest +from .types.registration_service import ListEndpointsResponse +from .types.registration_service import ListNamespacesRequest +from .types.registration_service import ListNamespacesResponse +from .types.registration_service import ListServicesRequest +from .types.registration_service import ListServicesResponse +from .types.registration_service import UpdateEndpointRequest +from .types.registration_service import UpdateNamespaceRequest +from .types.registration_service import UpdateServiceRequest +from .types.service import Service + +__all__ = ( + 'LookupServiceAsyncClient', + 'RegistrationServiceAsyncClient', +'CreateEndpointRequest', +'CreateNamespaceRequest', +'CreateServiceRequest', +'DeleteEndpointRequest', +'DeleteNamespaceRequest', +'DeleteServiceRequest', +'Endpoint', +'GetEndpointRequest', +'GetNamespaceRequest', +'GetServiceRequest', +'ListEndpointsRequest', +'ListEndpointsResponse', +'ListNamespacesRequest', +'ListNamespacesResponse', +'ListServicesRequest', +'ListServicesResponse', +'LookupServiceClient', +'Namespace', +'RegistrationServiceClient', +'ResolveServiceRequest', +'ResolveServiceResponse', +'Service', +'UpdateEndpointRequest', +'UpdateNamespaceRequest', +'UpdateServiceRequest', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/gapic_metadata.json new file mode 100644 index 00000000..be064678 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/gapic_metadata.json @@ -0,0 +1,227 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.servicedirectory_v1beta1", + "protoPackage": "google.cloud.servicedirectory.v1beta1", + "schema": "1.0", + "services": { + "LookupService": { + "clients": { + "grpc": { + "libraryClient": "LookupServiceClient", + "rpcs": { + "ResolveService": { + "methods": [ + "resolve_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LookupServiceAsyncClient", + "rpcs": { + "ResolveService": { + "methods": [ + "resolve_service" + ] + } + } + } + } + }, + "RegistrationService": { + "clients": { + "grpc": { + "libraryClient": "RegistrationServiceClient", + "rpcs": { + "CreateEndpoint": { + "methods": [ + "create_endpoint" + ] + }, + "CreateNamespace": { + "methods": [ + "create_namespace" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteEndpoint": { + "methods": [ + "delete_endpoint" + ] + }, + "DeleteNamespace": { + "methods": [ + "delete_namespace" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetEndpoint": { + "methods": [ + "get_endpoint" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNamespace": { + "methods": [ + "get_namespace" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListEndpoints": { + "methods": [ + "list_endpoints" + ] + }, + "ListNamespaces": { + "methods": [ + "list_namespaces" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateEndpoint": { + "methods": [ + "update_endpoint" + ] + }, + "UpdateNamespace": { + "methods": [ + "update_namespace" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RegistrationServiceAsyncClient", + "rpcs": { + "CreateEndpoint": { + "methods": [ + "create_endpoint" + ] + }, + "CreateNamespace": { + "methods": [ + "create_namespace" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteEndpoint": { + "methods": [ + "delete_endpoint" + ] + }, + "DeleteNamespace": { + "methods": [ + "delete_namespace" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetEndpoint": { + "methods": [ + "get_endpoint" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNamespace": { + "methods": [ + "get_namespace" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListEndpoints": { + "methods": [ + "list_endpoints" + ] + }, + "ListNamespaces": { + "methods": [ + "list_namespaces" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateEndpoint": { + "methods": [ + "update_endpoint" + ] + }, + "UpdateNamespace": { + "methods": [ + "update_namespace" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/py.typed new file mode 100644 index 00000000..8a62d150 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-service-directory package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py new file mode 100644 index 00000000..926753ac --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 LookupServiceClient +from .async_client import LookupServiceAsyncClient + +__all__ = ( + 'LookupServiceClient', + 'LookupServiceAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py new file mode 100644 index 00000000..016b82b2 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py @@ -0,0 +1,229 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import lookup_service +from google.cloud.servicedirectory_v1beta1.types import service +from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport +from .client import LookupServiceClient + + +class LookupServiceAsyncClient: + """Service Directory API for looking up service data at runtime.""" + + _client: LookupServiceClient + + DEFAULT_ENDPOINT = LookupServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LookupServiceClient.DEFAULT_MTLS_ENDPOINT + + endpoint_path = staticmethod(LookupServiceClient.endpoint_path) + parse_endpoint_path = staticmethod(LookupServiceClient.parse_endpoint_path) + network_path = staticmethod(LookupServiceClient.network_path) + parse_network_path = staticmethod(LookupServiceClient.parse_network_path) + service_path = staticmethod(LookupServiceClient.service_path) + parse_service_path = staticmethod(LookupServiceClient.parse_service_path) + common_billing_account_path = staticmethod(LookupServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LookupServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LookupServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(LookupServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(LookupServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(LookupServiceClient.parse_common_organization_path) + common_project_path = staticmethod(LookupServiceClient.common_project_path) + parse_common_project_path = staticmethod(LookupServiceClient.parse_common_project_path) + common_location_path = staticmethod(LookupServiceClient.common_location_path) + parse_common_location_path = staticmethod(LookupServiceClient.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: + LookupServiceAsyncClient: The constructed client. + """ + return LookupServiceClient.from_service_account_info.__func__(LookupServiceAsyncClient, 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: + LookupServiceAsyncClient: The constructed client. + """ + return LookupServiceClient.from_service_account_file.__func__(LookupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> LookupServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LookupServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(LookupServiceClient).get_transport_class, type(LookupServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, LookupServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lookup 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 (Union[str, ~.LookupServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = LookupServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def resolve_service(self, + request: lookup_service.ResolveServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lookup_service.ResolveServiceResponse: + r"""Returns a + [service][google.cloud.servicedirectory.v1beta1.Service] and its + associated endpoints. Resolving a service is not considered an + active developer method. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.ResolveServiceRequest`): + The request object. The request message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. + Looks up a service by its name, returns the service and + its endpoints. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.servicedirectory_v1beta1.types.ResolveServiceResponse: + The response message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. + + """ + # Create or coerce a protobuf request object. + request = lookup_service.ResolveServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.resolve_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "LookupServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py new file mode 100644 index 00000000..cdd3bdcf --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py @@ -0,0 +1,445 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +from google.cloud.servicedirectory_v1beta1.types import lookup_service +from google.cloud.servicedirectory_v1beta1.types import service +from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LookupServiceGrpcTransport +from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport + + +class LookupServiceClientMeta(type): + """Metaclass for the LookupService 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[LookupServiceTransport]] + _transport_registry["grpc"] = LookupServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LookupServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[LookupServiceTransport]: + """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 LookupServiceClient(metaclass=LookupServiceClientMeta): + """Service Directory API for looking up service data at runtime.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "servicedirectory.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LookupServiceClient: 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: + LookupServiceClient: 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) -> LookupServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LookupServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def endpoint_path(project: str,location: str,namespace: str,service: str,endpoint: str,) -> str: + """Returns a fully-qualified endpoint string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) + + @staticmethod + def parse_endpoint_path(path: str) -> Dict[str,str]: + """Parses a endpoint path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def network_path(project: str,network: str,) -> str: + """Returns a fully-qualified network string.""" + return "projects/{project}/locations/global/networks/{network}".format(project=project, network=network, ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str,str]: + """Parses a network path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/global/networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,namespace: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, LookupServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lookup 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 (Union[str, LookupServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, LookupServiceTransport): + # transport is a LookupServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def resolve_service(self, + request: Union[lookup_service.ResolveServiceRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lookup_service.ResolveServiceResponse: + r"""Returns a + [service][google.cloud.servicedirectory.v1beta1.Service] and its + associated endpoints. Resolving a service is not considered an + active developer method. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.ResolveServiceRequest, dict]): + The request object. The request message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. + Looks up a service by its name, returns the service and + its endpoints. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.servicedirectory_v1beta1.types.ResolveServiceResponse: + The response message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a lookup_service.ResolveServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, lookup_service.ResolveServiceRequest): + request = lookup_service.ResolveServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resolve_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "LookupServiceClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py new file mode 100644 index 00000000..437f5631 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 LookupServiceTransport +from .grpc import LookupServiceGrpcTransport +from .grpc_asyncio import LookupServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LookupServiceTransport]] +_transport_registry['grpc'] = LookupServiceGrpcTransport +_transport_registry['grpc_asyncio'] = LookupServiceGrpcAsyncIOTransport + +__all__ = ( + 'LookupServiceTransport', + 'LookupServiceGrpcTransport', + 'LookupServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py new file mode 100644 index 00000000..03732d5a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py @@ -0,0 +1,177 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import lookup_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-service-directory', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class LookupServiceTransport(abc.ABC): + """Abstract transport class for LookupService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'servicedirectory.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.resolve_service: gapic_v1.method.wrap_method( + self.resolve_service, + 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 resolve_service(self) -> Callable[ + [lookup_service.ResolveServiceRequest], + Union[ + lookup_service.ResolveServiceResponse, + Awaitable[lookup_service.ResolveServiceResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'LookupServiceTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py new file mode 100644 index 00000000..617e04f7 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py @@ -0,0 +1,257 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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.servicedirectory_v1beta1.types import lookup_service +from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO + + +class LookupServiceGrpcTransport(LookupServiceTransport): + """gRPC backend transport for LookupService. + + Service Directory API for looking up service data at runtime. + + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 resolve_service(self) -> Callable[ + [lookup_service.ResolveServiceRequest], + lookup_service.ResolveServiceResponse]: + r"""Return a callable for the resolve service method over gRPC. + + Returns a + [service][google.cloud.servicedirectory.v1beta1.Service] and its + associated endpoints. Resolving a service is not considered an + active developer method. + + Returns: + Callable[[~.ResolveServiceRequest], + ~.ResolveServiceResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'resolve_service' not in self._stubs: + self._stubs['resolve_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.LookupService/ResolveService', + request_serializer=lookup_service.ResolveServiceRequest.serialize, + response_deserializer=lookup_service.ResolveServiceResponse.deserialize, + ) + return self._stubs['resolve_service'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'LookupServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..96892495 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py @@ -0,0 +1,262 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import lookup_service +from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LookupServiceGrpcTransport + + +class LookupServiceGrpcAsyncIOTransport(LookupServiceTransport): + """gRPC AsyncIO backend transport for LookupService. + + Service Directory API for looking up service data at runtime. + + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def resolve_service(self) -> Callable[ + [lookup_service.ResolveServiceRequest], + Awaitable[lookup_service.ResolveServiceResponse]]: + r"""Return a callable for the resolve service method over gRPC. + + Returns a + [service][google.cloud.servicedirectory.v1beta1.Service] and its + associated endpoints. Resolving a service is not considered an + active developer method. + + Returns: + Callable[[~.ResolveServiceRequest], + Awaitable[~.ResolveServiceResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'resolve_service' not in self._stubs: + self._stubs['resolve_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.LookupService/ResolveService', + request_serializer=lookup_service.ResolveServiceRequest.serialize, + response_deserializer=lookup_service.ResolveServiceResponse.deserialize, + ) + return self._stubs['resolve_service'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'LookupServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py new file mode 100644 index 00000000..5097508c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 RegistrationServiceClient +from .async_client import RegistrationServiceAsyncClient + +__all__ = ( + 'RegistrationServiceClient', + 'RegistrationServiceAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py new file mode 100644 index 00000000..967760cd --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py @@ -0,0 +1,1740 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1beta1.services.registration_service import pagers +from google.cloud.servicedirectory_v1beta1.types import endpoint +from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace +from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1beta1.types import registration_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport +from .client import RegistrationServiceClient + + +class RegistrationServiceAsyncClient: + """Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1beta1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1beta1.Service] + resources, named + ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1beta1.Endpoint] + resources, named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + """ + + _client: RegistrationServiceClient + + DEFAULT_ENDPOINT = RegistrationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + + endpoint_path = staticmethod(RegistrationServiceClient.endpoint_path) + parse_endpoint_path = staticmethod(RegistrationServiceClient.parse_endpoint_path) + namespace_path = staticmethod(RegistrationServiceClient.namespace_path) + parse_namespace_path = staticmethod(RegistrationServiceClient.parse_namespace_path) + network_path = staticmethod(RegistrationServiceClient.network_path) + parse_network_path = staticmethod(RegistrationServiceClient.parse_network_path) + service_path = staticmethod(RegistrationServiceClient.service_path) + parse_service_path = staticmethod(RegistrationServiceClient.parse_service_path) + common_billing_account_path = staticmethod(RegistrationServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RegistrationServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RegistrationServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(RegistrationServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(RegistrationServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(RegistrationServiceClient.parse_common_organization_path) + common_project_path = staticmethod(RegistrationServiceClient.common_project_path) + parse_common_project_path = staticmethod(RegistrationServiceClient.parse_common_project_path) + common_location_path = staticmethod(RegistrationServiceClient.common_location_path) + parse_common_location_path = staticmethod(RegistrationServiceClient.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: + RegistrationServiceAsyncClient: The constructed client. + """ + return RegistrationServiceClient.from_service_account_info.__func__(RegistrationServiceAsyncClient, 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: + RegistrationServiceAsyncClient: The constructed client. + """ + return RegistrationServiceClient.from_service_account_file.__func__(RegistrationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RegistrationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegistrationServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RegistrationServiceClient).get_transport_class, type(RegistrationServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, RegistrationServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the registration 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 (Union[str, ~.RegistrationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RegistrationServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_namespace(self, + request: registration_service.CreateNamespaceRequest = None, + *, + parent: str = None, + namespace: gcs_namespace.Namespace = None, + namespace_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Creates a namespace, and returns the new namespace. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.CreateNamespaceRequest`): + The request object. The request message for + [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateNamespace]. + parent (:class:`str`): + Required. The resource name of the + project and location the namespace will + be created in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace (:class:`google.cloud.servicedirectory_v1beta1.types.Namespace`): + Required. A namespace with initial + fields set. + + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``namespace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1beta1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, namespace, namespace_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.CreateNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if namespace is not None: + request.namespace = namespace + if namespace_id is not None: + request.namespace_id = namespace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_namespaces(self, + request: registration_service.ListNamespacesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNamespacesAsyncPager: + r"""Lists all namespaces. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.ListNamespacesRequest`): + The request object. The request message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. + parent (:class:`str`): + Required. The resource name of the + project and location whose namespaces + you'd like to list. + + 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.servicedirectory_v1beta1.services.registration_service.pagers.ListNamespacesAsyncPager: + The response message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.ListNamespacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_namespaces, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListNamespacesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_namespace(self, + request: registration_service.GetNamespaceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> namespace.Namespace: + r"""Gets a namespace. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.GetNamespaceRequest`): + The request object. The request message for + [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.GetNamespace]. + name (:class:`str`): + Required. The name of the namespace + to retrieve. + + 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.servicedirectory_v1beta1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1beta1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.GetNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_namespace(self, + request: registration_service.UpdateNamespaceRequest = None, + *, + namespace: gcs_namespace.Namespace = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Updates a namespace. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.UpdateNamespaceRequest`): + The request object. The request message for + [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateNamespace]. + namespace (:class:`google.cloud.servicedirectory_v1beta1.types.Namespace`): + Required. The updated namespace. + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1beta1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([namespace, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.UpdateNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if namespace is not None: + request.namespace = namespace + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("namespace.name", request.namespace.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_namespace(self, + request: registration_service.DeleteNamespaceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.DeleteNamespaceRequest`): + The request object. The request message for + [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteNamespace]. + name (:class:`str`): + Required. The name of the namespace + to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.DeleteNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_service(self, + request: registration_service.CreateServiceRequest = None, + *, + parent: str = None, + service: gcs_service.Service = None, + service_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Creates a service, and returns the new service. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.CreateServiceRequest`): + The request object. The request message for + [RegistrationService.CreateService][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateService]. + parent (:class:`str`): + Required. The resource name of the + namespace this service will belong to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (:class:`google.cloud.servicedirectory_v1beta1.types.Service`): + Required. A service with initial + fields set. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.CreateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_services(self, + request: registration_service.ListServicesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesAsyncPager: + r"""Lists all services belonging to a namespace. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.ListServicesRequest`): + The request object. The request message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. + parent (:class:`str`): + Required. The resource name of the + namespace whose services you'd like to + list. + + 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.servicedirectory_v1beta1.services.registration_service.pagers.ListServicesAsyncPager: + The response message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.ListServicesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_services, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServicesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service(self, + request: registration_service.GetServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets a service. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.GetServiceRequest`): + The request object. The request message for + [RegistrationService.GetService][google.cloud.servicedirectory.v1beta1.RegistrationService.GetService]. + This should not be used for looking up a service. + Insead, use the `resolve` method as it contains all + endpoints and associated metadata. + name (:class:`str`): + Required. The name of the service to + get. + + 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.servicedirectory_v1beta1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.GetServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_service(self, + request: registration_service.UpdateServiceRequest = None, + *, + service: gcs_service.Service = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Updates a service. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.UpdateServiceRequest`): + The request object. The request message for + [RegistrationService.UpdateService][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateService]. + service (:class:`google.cloud.servicedirectory_v1beta1.types.Service`): + Required. The updated service. + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.UpdateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_service(self, + request: registration_service.DeleteServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a service. This also deletes all endpoints + associated with the service. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.DeleteServiceRequest`): + The request object. The request message for + [RegistrationService.DeleteService][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteService]. + name (:class:`str`): + Required. The name of the service to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.DeleteServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_endpoint(self, + request: registration_service.CreateEndpointRequest = None, + *, + parent: str = None, + endpoint: gcs_endpoint.Endpoint = None, + endpoint_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Creates an endpoint, and returns the new endpoint. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.CreateEndpointRequest`): + The request object. The request message for + [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateEndpoint]. + parent (:class:`str`): + Required. The resource name of the + service that this endpoint provides. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint (:class:`google.cloud.servicedirectory_v1beta1.types.Endpoint`): + Required. A endpoint with initial + fields set. + + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1beta1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, endpoint, endpoint_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.CreateEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if endpoint is not None: + request.endpoint = endpoint + if endpoint_id is not None: + request.endpoint_id = endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_endpoints(self, + request: registration_service.ListEndpointsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEndpointsAsyncPager: + r"""Lists all endpoints. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.ListEndpointsRequest`): + The request object. The request message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. + parent (:class:`str`): + Required. The resource name of the + service whose endpoints you'd like to + list. + + 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.servicedirectory_v1beta1.services.registration_service.pagers.ListEndpointsAsyncPager: + The response message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.ListEndpointsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_endpoints, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEndpointsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_endpoint(self, + request: registration_service.GetEndpointRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint.Endpoint: + r"""Gets an endpoint. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.GetEndpointRequest`): + The request object. The request message for + [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.GetEndpoint]. + This should not be used to lookup endpoints at runtime. + Instead, use the `resolve` method. + name (:class:`str`): + Required. The name of the endpoint to + get. + + 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.servicedirectory_v1beta1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1beta1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.GetEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_endpoint(self, + request: registration_service.UpdateEndpointRequest = None, + *, + endpoint: gcs_endpoint.Endpoint = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Updates an endpoint. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.UpdateEndpointRequest`): + The request object. The request message for + [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateEndpoint]. + endpoint (:class:`google.cloud.servicedirectory_v1beta1.types.Endpoint`): + Required. The updated endpoint. + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1beta1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([endpoint, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.UpdateEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if endpoint is not None: + request.endpoint = endpoint + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("endpoint.name", request.endpoint.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_endpoint(self, + request: registration_service.DeleteEndpointRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an endpoint. + + Args: + request (:class:`google.cloud.servicedirectory_v1beta1.types.DeleteEndpointRequest`): + The request object. The request message for + [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteEndpoint]. + name (:class:`str`): + Required. The name of the endpoint to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registration_service.DeleteEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_iam_policy(self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM Policy for a resource (namespace or + service only). + + Args: + request (:class:`google.iam.v1.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: + google.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy(self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM Policy for a resource (namespace or + service only). + + Args: + request (:class:`google.iam.v1.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: + google.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions(self, + request: iam_policy_pb2.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests IAM permissions for a resource (namespace or + service only). + + Args: + request (:class:`google.iam.v1.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: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "RegistrationServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py new file mode 100644 index 00000000..532efd4d --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py @@ -0,0 +1,1961 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +from google.cloud.servicedirectory_v1beta1.services.registration_service import pagers +from google.cloud.servicedirectory_v1beta1.types import endpoint +from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace +from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1beta1.types import registration_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RegistrationServiceGrpcTransport +from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport + + +class RegistrationServiceClientMeta(type): + """Metaclass for the RegistrationService 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[RegistrationServiceTransport]] + _transport_registry["grpc"] = RegistrationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RegistrationServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[RegistrationServiceTransport]: + """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 RegistrationServiceClient(metaclass=RegistrationServiceClientMeta): + """Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1beta1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1beta1.Service] + resources, named + ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1beta1.Endpoint] + resources, named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "servicedirectory.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegistrationServiceClient: 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: + RegistrationServiceClient: 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) -> RegistrationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegistrationServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def endpoint_path(project: str,location: str,namespace: str,service: str,endpoint: str,) -> str: + """Returns a fully-qualified endpoint string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) + + @staticmethod + def parse_endpoint_path(path: str) -> Dict[str,str]: + """Parses a endpoint path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def namespace_path(project: str,location: str,namespace: str,) -> str: + """Returns a fully-qualified namespace string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}".format(project=project, location=location, namespace=namespace, ) + + @staticmethod + def parse_namespace_path(path: str) -> Dict[str,str]: + """Parses a namespace path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def network_path(project: str,network: str,) -> str: + """Returns a fully-qualified network string.""" + return "projects/{project}/locations/global/networks/{network}".format(project=project, network=network, ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str,str]: + """Parses a network path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/global/networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,namespace: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RegistrationServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the registration 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 (Union[str, RegistrationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RegistrationServiceTransport): + # transport is a RegistrationServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_namespace(self, + request: Union[registration_service.CreateNamespaceRequest, dict] = None, + *, + parent: str = None, + namespace: gcs_namespace.Namespace = None, + namespace_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Creates a namespace, and returns the new namespace. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.CreateNamespaceRequest, dict]): + The request object. The request message for + [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateNamespace]. + parent (str): + Required. The resource name of the + project and location the namespace will + be created in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace (google.cloud.servicedirectory_v1beta1.types.Namespace): + Required. A namespace with initial + fields set. + + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace_id (str): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``namespace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1beta1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, namespace, namespace_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateNamespaceRequest): + request = registration_service.CreateNamespaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if namespace is not None: + request.namespace = namespace + if namespace_id is not None: + request.namespace_id = namespace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_namespaces(self, + request: Union[registration_service.ListNamespacesRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNamespacesPager: + r"""Lists all namespaces. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.ListNamespacesRequest, dict]): + The request object. The request message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. + parent (str): + Required. The resource name of the + project and location whose namespaces + you'd like to list. + + 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.servicedirectory_v1beta1.services.registration_service.pagers.ListNamespacesPager: + The response message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListNamespacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListNamespacesRequest): + request = registration_service.ListNamespacesRequest(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_namespaces] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListNamespacesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_namespace(self, + request: Union[registration_service.GetNamespaceRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> namespace.Namespace: + r"""Gets a namespace. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.GetNamespaceRequest, dict]): + The request object. The request message for + [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.GetNamespace]. + name (str): + Required. The name of the namespace + to retrieve. + + 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.servicedirectory_v1beta1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1beta1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetNamespaceRequest): + request = registration_service.GetNamespaceRequest(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_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_namespace(self, + request: Union[registration_service.UpdateNamespaceRequest, dict] = None, + *, + namespace: gcs_namespace.Namespace = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Updates a namespace. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.UpdateNamespaceRequest, dict]): + The request object. The request message for + [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateNamespace]. + namespace (google.cloud.servicedirectory_v1beta1.types.Namespace): + Required. The updated namespace. + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Namespace: + A container for [services][google.cloud.servicedirectory.v1beta1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([namespace, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateNamespaceRequest): + request = registration_service.UpdateNamespaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if namespace is not None: + request.namespace = namespace + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("namespace.name", request.namespace.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_namespace(self, + request: Union[registration_service.DeleteNamespaceRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.DeleteNamespaceRequest, dict]): + The request object. The request message for + [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteNamespace]. + name (str): + Required. The name of the namespace + to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteNamespaceRequest): + request = registration_service.DeleteNamespaceRequest(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_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_service(self, + request: Union[registration_service.CreateServiceRequest, dict] = None, + *, + parent: str = None, + service: gcs_service.Service = None, + service_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Creates a service, and returns the new service. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.CreateServiceRequest, dict]): + The request object. The request message for + [RegistrationService.CreateService][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateService]. + parent (str): + Required. The resource name of the + namespace this service will belong to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (google.cloud.servicedirectory_v1beta1.types.Service): + Required. A service with initial + fields set. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (str): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateServiceRequest): + request = registration_service.CreateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_services(self, + request: Union[registration_service.ListServicesRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesPager: + r"""Lists all services belonging to a namespace. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.ListServicesRequest, dict]): + The request object. The request message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. + parent (str): + Required. The resource name of the + namespace whose services you'd like to + list. + + 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.servicedirectory_v1beta1.services.registration_service.pagers.ListServicesPager: + The response message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListServicesRequest): + request = registration_service.ListServicesRequest(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_services] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServicesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service(self, + request: Union[registration_service.GetServiceRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets a service. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.GetServiceRequest, dict]): + The request object. The request message for + [RegistrationService.GetService][google.cloud.servicedirectory.v1beta1.RegistrationService.GetService]. + This should not be used for looking up a service. + Insead, use the `resolve` method as it contains all + endpoints and associated metadata. + name (str): + Required. The name of the service to + get. + + 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.servicedirectory_v1beta1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetServiceRequest): + request = registration_service.GetServiceRequest(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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_service(self, + request: Union[registration_service.UpdateServiceRequest, dict] = None, + *, + service: gcs_service.Service = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Updates a service. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.UpdateServiceRequest, dict]): + The request object. The request message for + [RegistrationService.UpdateService][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateService]. + service (google.cloud.servicedirectory_v1beta1.types.Service): + Required. The updated service. + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Service: + An individual service. A service contains a name and optional metadata. + A service must exist before + [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateServiceRequest): + request = registration_service.UpdateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_service(self, + request: Union[registration_service.DeleteServiceRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a service. This also deletes all endpoints + associated with the service. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.DeleteServiceRequest, dict]): + The request object. The request message for + [RegistrationService.DeleteService][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteService]. + name (str): + Required. The name of the service to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteServiceRequest): + request = registration_service.DeleteServiceRequest(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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_endpoint(self, + request: Union[registration_service.CreateEndpointRequest, dict] = None, + *, + parent: str = None, + endpoint: gcs_endpoint.Endpoint = None, + endpoint_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Creates an endpoint, and returns the new endpoint. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.CreateEndpointRequest, dict]): + The request object. The request message for + [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateEndpoint]. + parent (str): + Required. The resource name of the + service that this endpoint provides. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint (google.cloud.servicedirectory_v1beta1.types.Endpoint): + Required. A endpoint with initial + fields set. + + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_id (str): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1beta1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, endpoint, endpoint_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateEndpointRequest): + request = registration_service.CreateEndpointRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if endpoint is not None: + request.endpoint = endpoint + if endpoint_id is not None: + request.endpoint_id = endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_endpoints(self, + request: Union[registration_service.ListEndpointsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEndpointsPager: + r"""Lists all endpoints. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.ListEndpointsRequest, dict]): + The request object. The request message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. + parent (str): + Required. The resource name of the + service whose endpoints you'd like to + list. + + 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.servicedirectory_v1beta1.services.registration_service.pagers.ListEndpointsPager: + The response message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListEndpointsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListEndpointsRequest): + request = registration_service.ListEndpointsRequest(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_endpoints] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEndpointsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_endpoint(self, + request: Union[registration_service.GetEndpointRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint.Endpoint: + r"""Gets an endpoint. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.GetEndpointRequest, dict]): + The request object. The request message for + [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.GetEndpoint]. + This should not be used to lookup endpoints at runtime. + Instead, use the `resolve` method. + name (str): + Required. The name of the endpoint to + get. + + 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.servicedirectory_v1beta1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1beta1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetEndpointRequest): + request = registration_service.GetEndpointRequest(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_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_endpoint(self, + request: Union[registration_service.UpdateEndpointRequest, dict] = None, + *, + endpoint: gcs_endpoint.Endpoint = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Updates an endpoint. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.UpdateEndpointRequest, dict]): + The request object. The request message for + [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateEndpoint]. + endpoint (google.cloud.servicedirectory_v1beta1.types.Endpoint): + Required. The updated endpoint. + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.servicedirectory_v1beta1.types.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1beta1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([endpoint, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateEndpointRequest): + request = registration_service.UpdateEndpointRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if endpoint is not None: + request.endpoint = endpoint + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("endpoint.name", request.endpoint.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_endpoint(self, + request: Union[registration_service.DeleteEndpointRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an endpoint. + + Args: + request (Union[google.cloud.servicedirectory_v1beta1.types.DeleteEndpointRequest, dict]): + The request object. The request message for + [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteEndpoint]. + name (str): + Required. The name of the endpoint to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteEndpointRequest): + request = registration_service.DeleteEndpointRequest(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_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM Policy for a resource (namespace or + service only). + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + 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: + google.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy(self, + request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM Policy for a resource (namespace or + service only). + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + 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: + google.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions(self, + request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests IAM permissions for a resource (namespace or + service only). + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + 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: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "RegistrationServiceClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py new file mode 100644 index 00000000..13ccc6ca --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py @@ -0,0 +1,387 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.servicedirectory_v1beta1.types import endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace +from google.cloud.servicedirectory_v1beta1.types import registration_service +from google.cloud.servicedirectory_v1beta1.types import service + + +class ListNamespacesPager: + """A pager for iterating through ``list_namespaces`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``namespaces`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNamespaces`` requests and continue to iterate + through the ``namespaces`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse` + 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[..., registration_service.ListNamespacesResponse], + request: registration_service.ListNamespacesRequest, + response: registration_service.ListNamespacesResponse, + *, + 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.servicedirectory_v1beta1.types.ListNamespacesRequest): + The initial request object. + response (google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListNamespacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registration_service.ListNamespacesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[namespace.Namespace]: + for page in self.pages: + yield from page.namespaces + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNamespacesAsyncPager: + """A pager for iterating through ``list_namespaces`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``namespaces`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNamespaces`` requests and continue to iterate + through the ``namespaces`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse` + 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[registration_service.ListNamespacesResponse]], + request: registration_service.ListNamespacesRequest, + response: registration_service.ListNamespacesResponse, + *, + 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.servicedirectory_v1beta1.types.ListNamespacesRequest): + The initial request object. + response (google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListNamespacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registration_service.ListNamespacesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[namespace.Namespace]: + async def async_generator(): + async for page in self.pages: + for response in page.namespaces: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServicesPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1beta1.types.ListServicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListServicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., registration_service.ListServicesResponse], + request: registration_service.ListServicesRequest, + response: registration_service.ListServicesResponse, + *, + 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.servicedirectory_v1beta1.types.ListServicesRequest): + The initial request object. + response (google.cloud.servicedirectory_v1beta1.types.ListServicesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registration_service.ListServicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[service.Service]: + for page in self.pages: + yield from page.services + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServicesAsyncPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1beta1.types.ListServicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListServicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[registration_service.ListServicesResponse]], + request: registration_service.ListServicesRequest, + response: registration_service.ListServicesResponse, + *, + 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.servicedirectory_v1beta1.types.ListServicesRequest): + The initial request object. + response (google.cloud.servicedirectory_v1beta1.types.ListServicesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registration_service.ListServicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[service.Service]: + async def async_generator(): + async for page in self.pages: + for response in page.services: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEndpointsPager: + """A pager for iterating through ``list_endpoints`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``endpoints`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEndpoints`` requests and continue to iterate + through the ``endpoints`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse` + 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[..., registration_service.ListEndpointsResponse], + request: registration_service.ListEndpointsRequest, + response: registration_service.ListEndpointsResponse, + *, + 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.servicedirectory_v1beta1.types.ListEndpointsRequest): + The initial request object. + response (google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListEndpointsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registration_service.ListEndpointsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[endpoint.Endpoint]: + for page in self.pages: + yield from page.endpoints + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEndpointsAsyncPager: + """A pager for iterating through ``list_endpoints`` requests. + + This class thinly wraps an initial + :class:`google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``endpoints`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEndpoints`` requests and continue to iterate + through the ``endpoints`` field on the + corresponding responses. + + All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse` + 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[registration_service.ListEndpointsResponse]], + request: registration_service.ListEndpointsRequest, + response: registration_service.ListEndpointsResponse, + *, + 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.servicedirectory_v1beta1.types.ListEndpointsRequest): + The initial request object. + response (google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListEndpointsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registration_service.ListEndpointsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[endpoint.Endpoint]: + async def async_generator(): + async for page in self.pages: + for response in page.endpoints: + 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/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py new file mode 100644 index 00000000..a584bf16 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 RegistrationServiceTransport +from .grpc import RegistrationServiceGrpcTransport +from .grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RegistrationServiceTransport]] +_transport_registry['grpc'] = RegistrationServiceGrpcTransport +_transport_registry['grpc_asyncio'] = RegistrationServiceGrpcAsyncIOTransport + +__all__ = ( + 'RegistrationServiceTransport', + 'RegistrationServiceGrpcTransport', + 'RegistrationServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py new file mode 100644 index 00000000..79d45c98 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py @@ -0,0 +1,424 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import endpoint +from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace +from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1beta1.types import registration_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-service-directory', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class RegistrationServiceTransport(abc.ABC): + """Abstract transport class for RegistrationService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'servicedirectory.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_namespace: gapic_v1.method.wrap_method( + self.create_namespace, + default_timeout=None, + client_info=client_info, + ), + self.list_namespaces: gapic_v1.method.wrap_method( + self.list_namespaces, + default_timeout=None, + client_info=client_info, + ), + self.get_namespace: gapic_v1.method.wrap_method( + self.get_namespace, + default_timeout=None, + client_info=client_info, + ), + self.update_namespace: gapic_v1.method.wrap_method( + self.update_namespace, + default_timeout=None, + client_info=client_info, + ), + self.delete_namespace: gapic_v1.method.wrap_method( + self.delete_namespace, + default_timeout=None, + client_info=client_info, + ), + self.create_service: gapic_v1.method.wrap_method( + self.create_service, + default_timeout=None, + client_info=client_info, + ), + self.list_services: gapic_v1.method.wrap_method( + self.list_services, + default_timeout=None, + client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, + default_timeout=None, + client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, + default_timeout=None, + client_info=client_info, + ), + self.delete_service: gapic_v1.method.wrap_method( + self.delete_service, + default_timeout=None, + client_info=client_info, + ), + self.create_endpoint: gapic_v1.method.wrap_method( + self.create_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.list_endpoints: gapic_v1.method.wrap_method( + self.list_endpoints, + default_timeout=None, + client_info=client_info, + ), + self.get_endpoint: gapic_v1.method.wrap_method( + self.get_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.update_endpoint: gapic_v1.method.wrap_method( + self.update_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.delete_endpoint: gapic_v1.method.wrap_method( + self.delete_endpoint, + 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, + ), + } + + 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 create_namespace(self) -> Callable[ + [registration_service.CreateNamespaceRequest], + Union[ + gcs_namespace.Namespace, + Awaitable[gcs_namespace.Namespace] + ]]: + raise NotImplementedError() + + @property + def list_namespaces(self) -> Callable[ + [registration_service.ListNamespacesRequest], + Union[ + registration_service.ListNamespacesResponse, + Awaitable[registration_service.ListNamespacesResponse] + ]]: + raise NotImplementedError() + + @property + def get_namespace(self) -> Callable[ + [registration_service.GetNamespaceRequest], + Union[ + namespace.Namespace, + Awaitable[namespace.Namespace] + ]]: + raise NotImplementedError() + + @property + def update_namespace(self) -> Callable[ + [registration_service.UpdateNamespaceRequest], + Union[ + gcs_namespace.Namespace, + Awaitable[gcs_namespace.Namespace] + ]]: + raise NotImplementedError() + + @property + def delete_namespace(self) -> Callable[ + [registration_service.DeleteNamespaceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_service(self) -> Callable[ + [registration_service.CreateServiceRequest], + Union[ + gcs_service.Service, + Awaitable[gcs_service.Service] + ]]: + raise NotImplementedError() + + @property + def list_services(self) -> Callable[ + [registration_service.ListServicesRequest], + Union[ + registration_service.ListServicesResponse, + Awaitable[registration_service.ListServicesResponse] + ]]: + raise NotImplementedError() + + @property + def get_service(self) -> Callable[ + [registration_service.GetServiceRequest], + Union[ + service.Service, + Awaitable[service.Service] + ]]: + raise NotImplementedError() + + @property + def update_service(self) -> Callable[ + [registration_service.UpdateServiceRequest], + Union[ + gcs_service.Service, + Awaitable[gcs_service.Service] + ]]: + raise NotImplementedError() + + @property + def delete_service(self) -> Callable[ + [registration_service.DeleteServiceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_endpoint(self) -> Callable[ + [registration_service.CreateEndpointRequest], + Union[ + gcs_endpoint.Endpoint, + Awaitable[gcs_endpoint.Endpoint] + ]]: + raise NotImplementedError() + + @property + def list_endpoints(self) -> Callable[ + [registration_service.ListEndpointsRequest], + Union[ + registration_service.ListEndpointsResponse, + Awaitable[registration_service.ListEndpointsResponse] + ]]: + raise NotImplementedError() + + @property + def get_endpoint(self) -> Callable[ + [registration_service.GetEndpointRequest], + Union[ + endpoint.Endpoint, + Awaitable[endpoint.Endpoint] + ]]: + raise NotImplementedError() + + @property + def update_endpoint(self) -> Callable[ + [registration_service.UpdateEndpointRequest], + Union[ + gcs_endpoint.Endpoint, + Awaitable[gcs_endpoint.Endpoint] + ]]: + raise NotImplementedError() + + @property + def delete_endpoint(self) -> Callable[ + [registration_service.DeleteEndpointRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + 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 set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + 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() + + +__all__ = ( + 'RegistrationServiceTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py new file mode 100644 index 00000000..0d49c0ae --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py @@ -0,0 +1,725 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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.servicedirectory_v1beta1.types import endpoint +from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace +from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1beta1.types import registration_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO + + +class RegistrationServiceGrpcTransport(RegistrationServiceTransport): + """gRPC backend transport for RegistrationService. + + Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1beta1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1beta1.Service] + resources, named + ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1beta1.Endpoint] + resources, named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 create_namespace(self) -> Callable[ + [registration_service.CreateNamespaceRequest], + gcs_namespace.Namespace]: + r"""Return a callable for the create namespace method over gRPC. + + Creates a namespace, and returns the new namespace. + + Returns: + Callable[[~.CreateNamespaceRequest], + ~.Namespace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['create_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateNamespace', + request_serializer=registration_service.CreateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs['create_namespace'] + + @property + def list_namespaces(self) -> Callable[ + [registration_service.ListNamespacesRequest], + registration_service.ListNamespacesResponse]: + r"""Return a callable for the list namespaces method over gRPC. + + Lists all namespaces. + + Returns: + Callable[[~.ListNamespacesRequest], + ~.ListNamespacesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespaces' not in self._stubs: + self._stubs['list_namespaces'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListNamespaces', + request_serializer=registration_service.ListNamespacesRequest.serialize, + response_deserializer=registration_service.ListNamespacesResponse.deserialize, + ) + return self._stubs['list_namespaces'] + + @property + def get_namespace(self) -> Callable[ + [registration_service.GetNamespaceRequest], + namespace.Namespace]: + r"""Return a callable for the get namespace method over gRPC. + + Gets a namespace. + + Returns: + Callable[[~.GetNamespaceRequest], + ~.Namespace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['get_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetNamespace', + request_serializer=registration_service.GetNamespaceRequest.serialize, + response_deserializer=namespace.Namespace.deserialize, + ) + return self._stubs['get_namespace'] + + @property + def update_namespace(self) -> Callable[ + [registration_service.UpdateNamespaceRequest], + gcs_namespace.Namespace]: + r"""Return a callable for the update namespace method over gRPC. + + Updates a namespace. + + Returns: + Callable[[~.UpdateNamespaceRequest], + ~.Namespace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['update_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateNamespace', + request_serializer=registration_service.UpdateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs['update_namespace'] + + @property + def delete_namespace(self) -> Callable[ + [registration_service.DeleteNamespaceRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete namespace method over gRPC. + + Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Returns: + Callable[[~.DeleteNamespaceRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_namespace' not in self._stubs: + self._stubs['delete_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteNamespace', + request_serializer=registration_service.DeleteNamespaceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_namespace'] + + @property + def create_service(self) -> Callable[ + [registration_service.CreateServiceRequest], + gcs_service.Service]: + r"""Return a callable for the create service method over gRPC. + + Creates a service, and returns the new service. + + Returns: + Callable[[~.CreateServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateService', + request_serializer=registration_service.CreateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs['create_service'] + + @property + def list_services(self) -> Callable[ + [registration_service.ListServicesRequest], + registration_service.ListServicesResponse]: + r"""Return a callable for the list services method over gRPC. + + Lists all services belonging to a namespace. + + Returns: + Callable[[~.ListServicesRequest], + ~.ListServicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListServices', + request_serializer=registration_service.ListServicesRequest.serialize, + response_deserializer=registration_service.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [registration_service.GetServiceRequest], + service.Service]: + r"""Return a callable for the get service method over gRPC. + + Gets a service. + + Returns: + Callable[[~.GetServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetService', + request_serializer=registration_service.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def update_service(self) -> Callable[ + [registration_service.UpdateServiceRequest], + gcs_service.Service]: + r"""Return a callable for the update service method over gRPC. + + Updates a service. + + Returns: + Callable[[~.UpdateServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateService', + request_serializer=registration_service.UpdateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [registration_service.DeleteServiceRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a service. This also deletes all endpoints + associated with the service. + + Returns: + Callable[[~.DeleteServiceRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteService', + request_serializer=registration_service.DeleteServiceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_service'] + + @property + def create_endpoint(self) -> Callable[ + [registration_service.CreateEndpointRequest], + gcs_endpoint.Endpoint]: + r"""Return a callable for the create endpoint method over gRPC. + + Creates an endpoint, and returns the new endpoint. + + Returns: + Callable[[~.CreateEndpointRequest], + ~.Endpoint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['create_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateEndpoint', + request_serializer=registration_service.CreateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs['create_endpoint'] + + @property + def list_endpoints(self) -> Callable[ + [registration_service.ListEndpointsRequest], + registration_service.ListEndpointsResponse]: + r"""Return a callable for the list endpoints method over gRPC. + + Lists all endpoints. + + Returns: + Callable[[~.ListEndpointsRequest], + ~.ListEndpointsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoints' not in self._stubs: + self._stubs['list_endpoints'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListEndpoints', + request_serializer=registration_service.ListEndpointsRequest.serialize, + response_deserializer=registration_service.ListEndpointsResponse.deserialize, + ) + return self._stubs['list_endpoints'] + + @property + def get_endpoint(self) -> Callable[ + [registration_service.GetEndpointRequest], + endpoint.Endpoint]: + r"""Return a callable for the get endpoint method over gRPC. + + Gets an endpoint. + + Returns: + Callable[[~.GetEndpointRequest], + ~.Endpoint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['get_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetEndpoint', + request_serializer=registration_service.GetEndpointRequest.serialize, + response_deserializer=endpoint.Endpoint.deserialize, + ) + return self._stubs['get_endpoint'] + + @property + def update_endpoint(self) -> Callable[ + [registration_service.UpdateEndpointRequest], + gcs_endpoint.Endpoint]: + r"""Return a callable for the update endpoint method over gRPC. + + Updates an endpoint. + + Returns: + Callable[[~.UpdateEndpointRequest], + ~.Endpoint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['update_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateEndpoint', + request_serializer=registration_service.UpdateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs['update_endpoint'] + + @property + def delete_endpoint(self) -> Callable[ + [registration_service.DeleteEndpointRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete endpoint method over gRPC. + + Deletes an endpoint. + + Returns: + Callable[[~.DeleteEndpointRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_endpoint' not in self._stubs: + self._stubs['delete_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteEndpoint', + request_serializer=registration_service.DeleteEndpointRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_endpoint'] + + @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 Policy for a resource (namespace or + service only). + + 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.cloud.servicedirectory.v1beta1.RegistrationService/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 Policy for a resource (namespace or + service only). + + 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.cloud.servicedirectory.v1beta1.RegistrationService/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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 IAM permissions for a resource (namespace or + service only). + + 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.cloud.servicedirectory.v1beta1.RegistrationService/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'RegistrationServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..c729bdaa --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py @@ -0,0 +1,730 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import endpoint +from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace +from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1beta1.types import registration_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RegistrationServiceGrpcTransport + + +class RegistrationServiceGrpcAsyncIOTransport(RegistrationServiceTransport): + """gRPC AsyncIO backend transport for RegistrationService. + + Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1beta1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1beta1.Service] + resources, named + ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1beta1.Endpoint] + resources, named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + + 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 = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'servicedirectory.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_namespace(self) -> Callable[ + [registration_service.CreateNamespaceRequest], + Awaitable[gcs_namespace.Namespace]]: + r"""Return a callable for the create namespace method over gRPC. + + Creates a namespace, and returns the new namespace. + + Returns: + Callable[[~.CreateNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['create_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateNamespace', + request_serializer=registration_service.CreateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs['create_namespace'] + + @property + def list_namespaces(self) -> Callable[ + [registration_service.ListNamespacesRequest], + Awaitable[registration_service.ListNamespacesResponse]]: + r"""Return a callable for the list namespaces method over gRPC. + + Lists all namespaces. + + Returns: + Callable[[~.ListNamespacesRequest], + Awaitable[~.ListNamespacesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespaces' not in self._stubs: + self._stubs['list_namespaces'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListNamespaces', + request_serializer=registration_service.ListNamespacesRequest.serialize, + response_deserializer=registration_service.ListNamespacesResponse.deserialize, + ) + return self._stubs['list_namespaces'] + + @property + def get_namespace(self) -> Callable[ + [registration_service.GetNamespaceRequest], + Awaitable[namespace.Namespace]]: + r"""Return a callable for the get namespace method over gRPC. + + Gets a namespace. + + Returns: + Callable[[~.GetNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['get_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetNamespace', + request_serializer=registration_service.GetNamespaceRequest.serialize, + response_deserializer=namespace.Namespace.deserialize, + ) + return self._stubs['get_namespace'] + + @property + def update_namespace(self) -> Callable[ + [registration_service.UpdateNamespaceRequest], + Awaitable[gcs_namespace.Namespace]]: + r"""Return a callable for the update namespace method over gRPC. + + Updates a namespace. + + Returns: + Callable[[~.UpdateNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_namespace' not in self._stubs: + self._stubs['update_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateNamespace', + request_serializer=registration_service.UpdateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs['update_namespace'] + + @property + def delete_namespace(self) -> Callable[ + [registration_service.DeleteNamespaceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete namespace method over gRPC. + + Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Returns: + Callable[[~.DeleteNamespaceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_namespace' not in self._stubs: + self._stubs['delete_namespace'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteNamespace', + request_serializer=registration_service.DeleteNamespaceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_namespace'] + + @property + def create_service(self) -> Callable[ + [registration_service.CreateServiceRequest], + Awaitable[gcs_service.Service]]: + r"""Return a callable for the create service method over gRPC. + + Creates a service, and returns the new service. + + Returns: + Callable[[~.CreateServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateService', + request_serializer=registration_service.CreateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs['create_service'] + + @property + def list_services(self) -> Callable[ + [registration_service.ListServicesRequest], + Awaitable[registration_service.ListServicesResponse]]: + r"""Return a callable for the list services method over gRPC. + + Lists all services belonging to a namespace. + + Returns: + Callable[[~.ListServicesRequest], + Awaitable[~.ListServicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListServices', + request_serializer=registration_service.ListServicesRequest.serialize, + response_deserializer=registration_service.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [registration_service.GetServiceRequest], + Awaitable[service.Service]]: + r"""Return a callable for the get service method over gRPC. + + Gets a service. + + Returns: + Callable[[~.GetServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetService', + request_serializer=registration_service.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def update_service(self) -> Callable[ + [registration_service.UpdateServiceRequest], + Awaitable[gcs_service.Service]]: + r"""Return a callable for the update service method over gRPC. + + Updates a service. + + Returns: + Callable[[~.UpdateServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateService', + request_serializer=registration_service.UpdateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [registration_service.DeleteServiceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a service. This also deletes all endpoints + associated with the service. + + Returns: + Callable[[~.DeleteServiceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteService', + request_serializer=registration_service.DeleteServiceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_service'] + + @property + def create_endpoint(self) -> Callable[ + [registration_service.CreateEndpointRequest], + Awaitable[gcs_endpoint.Endpoint]]: + r"""Return a callable for the create endpoint method over gRPC. + + Creates an endpoint, and returns the new endpoint. + + Returns: + Callable[[~.CreateEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['create_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateEndpoint', + request_serializer=registration_service.CreateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs['create_endpoint'] + + @property + def list_endpoints(self) -> Callable[ + [registration_service.ListEndpointsRequest], + Awaitable[registration_service.ListEndpointsResponse]]: + r"""Return a callable for the list endpoints method over gRPC. + + Lists all endpoints. + + Returns: + Callable[[~.ListEndpointsRequest], + Awaitable[~.ListEndpointsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoints' not in self._stubs: + self._stubs['list_endpoints'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListEndpoints', + request_serializer=registration_service.ListEndpointsRequest.serialize, + response_deserializer=registration_service.ListEndpointsResponse.deserialize, + ) + return self._stubs['list_endpoints'] + + @property + def get_endpoint(self) -> Callable[ + [registration_service.GetEndpointRequest], + Awaitable[endpoint.Endpoint]]: + r"""Return a callable for the get endpoint method over gRPC. + + Gets an endpoint. + + Returns: + Callable[[~.GetEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['get_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetEndpoint', + request_serializer=registration_service.GetEndpointRequest.serialize, + response_deserializer=endpoint.Endpoint.deserialize, + ) + return self._stubs['get_endpoint'] + + @property + def update_endpoint(self) -> Callable[ + [registration_service.UpdateEndpointRequest], + Awaitable[gcs_endpoint.Endpoint]]: + r"""Return a callable for the update endpoint method over gRPC. + + Updates an endpoint. + + Returns: + Callable[[~.UpdateEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint' not in self._stubs: + self._stubs['update_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateEndpoint', + request_serializer=registration_service.UpdateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs['update_endpoint'] + + @property + def delete_endpoint(self) -> Callable[ + [registration_service.DeleteEndpointRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete endpoint method over gRPC. + + Deletes an endpoint. + + Returns: + Callable[[~.DeleteEndpointRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_endpoint' not in self._stubs: + self._stubs['delete_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteEndpoint', + request_serializer=registration_service.DeleteEndpointRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_endpoint'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM Policy for a resource (namespace or + service only). + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.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.cloud.servicedirectory.v1beta1.RegistrationService/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM Policy for a resource (namespace or + service only). + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.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.cloud.servicedirectory.v1beta1.RegistrationService/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests IAM permissions for a resource (namespace or + service only). + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.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.cloud.servicedirectory.v1beta1.RegistrationService/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'RegistrationServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/__init__.py new file mode 100644 index 00000000..acf22489 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/__init__.py @@ -0,0 +1,74 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .endpoint import ( + Endpoint, +) +from .lookup_service import ( + ResolveServiceRequest, + ResolveServiceResponse, +) +from .namespace import ( + Namespace, +) +from .registration_service import ( + CreateEndpointRequest, + CreateNamespaceRequest, + CreateServiceRequest, + DeleteEndpointRequest, + DeleteNamespaceRequest, + DeleteServiceRequest, + GetEndpointRequest, + GetNamespaceRequest, + GetServiceRequest, + ListEndpointsRequest, + ListEndpointsResponse, + ListNamespacesRequest, + ListNamespacesResponse, + ListServicesRequest, + ListServicesResponse, + UpdateEndpointRequest, + UpdateNamespaceRequest, + UpdateServiceRequest, +) +from .service import ( + Service, +) + +__all__ = ( + 'Endpoint', + 'ResolveServiceRequest', + 'ResolveServiceResponse', + 'Namespace', + 'CreateEndpointRequest', + 'CreateNamespaceRequest', + 'CreateServiceRequest', + 'DeleteEndpointRequest', + 'DeleteNamespaceRequest', + 'DeleteServiceRequest', + 'GetEndpointRequest', + 'GetNamespaceRequest', + 'GetServiceRequest', + 'ListEndpointsRequest', + 'ListEndpointsResponse', + 'ListNamespacesRequest', + 'ListNamespacesResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'UpdateEndpointRequest', + 'UpdateNamespaceRequest', + 'UpdateServiceRequest', + 'Service', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/endpoint.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/endpoint.py new file mode 100644 index 00000000..33890a47 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/endpoint.py @@ -0,0 +1,130 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.servicedirectory.v1beta1', + manifest={ + 'Endpoint', + }, +) + + +class Endpoint(proto.Message): + r"""An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1beta1.Service]. The + service must already exist to create an endpoint. + + Attributes: + name (str): + Immutable. The resource name for the endpoint in the format + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + address (str): + Optional. An IPv4 or IPv6 address. Service Directory rejects + bad addresses like: + + - ``8.8.8`` + - ``8.8.8.8:53`` + - ``test:bad:address`` + - ``[::1]`` + - ``[::1]:8080`` + + Limited to 45 characters. + port (int): + Optional. Service Directory rejects values outside of + ``[0, 65535]``. + metadata (Sequence[google.cloud.servicedirectory_v1beta1.types.Endpoint.MetadataEntry]): + Optional. Metadata for the endpoint. This data can be + consumed by service clients. + + Restrictions: + + - The entire metadata dictionary may contain up to 512 + characters, spread accoss all key-value pairs. Metadata + that goes beyond this limit are rejected + - Valid metadata keys have two segments: an optional prefix + and name, separated by a slash (/). The name segment is + required and must be 63 characters or less, beginning and + ending with an alphanumeric character ([a-z0-9A-Z]) with + dashes (-), underscores (_), dots (.), and alphanumerics + between. The prefix is optional. If specified, the prefix + must be a DNS subdomain: a series of DNS labels separated + by dots (.), not longer than 253 characters in total, + followed by a slash (/). Metadata that fails to meet + these requirements are rejected + - The ``(*.)google.com/`` and ``(*.)googleapis.com/`` + prefixes are reserved for system metadata managed by + Service Directory. If the user tries to write to these + keyspaces, those entries are silently ignored by the + system + + Note: This field is equivalent to the ``annotations`` field + in the v1 API. They have the same syntax and read/write to + the same location in Service Directory. + network (str): + Immutable. The Google Compute Engine network (VPC) of the + endpoint in the format + ``projects//locations/global/networks/*``. + + The project must be specified by project number (project id + is rejected). Incorrectly formatted networks are rejected, + but no other validation is performed on this field (ex. + network or project existence, reachability, or permissions). + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the endpoint + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the endpoint + was last updated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + address = proto.Field( + proto.STRING, + number=2, + ) + port = proto.Field( + proto.INT32, + number=3, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + network = proto.Field( + proto.STRING, + number=5, + ) + create_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/lookup_service.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/lookup_service.py new file mode 100644 index 00000000..01754f85 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/lookup_service.py @@ -0,0 +1,120 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service + + +__protobuf__ = proto.module( + package='google.cloud.servicedirectory.v1beta1', + manifest={ + 'ResolveServiceRequest', + 'ResolveServiceResponse', + }, +) + + +class ResolveServiceRequest(proto.Message): + r"""The request message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. + Looks up a service by its name, returns the service and its + endpoints. + + Attributes: + name (str): + Required. The name of the service to resolve. + max_endpoints (int): + Optional. The maximum number of endpoints to + return. Defaults to 25. Maximum is 100. If a + value less than one is specified, the Default is + used. If a value greater than the Maximum is + specified, the Maximum is used. + endpoint_filter (str): + Optional. The filter applied to the endpoints of the + resolved service. + + General ``filter`` string syntax: + `` ()`` + + - ```` can be ``name``, ``address``, ``port``, or + ``metadata.`` for map field + - ```` can be ``<``, ``>``, ``<=``, ``>=``, + ``!=``, ``=``, ``:``. Of which ``:`` means ``HAS``, and + is roughly the same as ``=`` + - ```` must be the same data type as field + - ```` can be ``AND``, ``OR``, ``NOT`` + + Examples of valid filters: + + - ``metadata.owner`` returns endpoints that have a + annotation with the key ``owner``, this is the same as + ``metadata:owner`` + - ``metadata.protocol=gRPC`` returns endpoints that have + key/value ``protocol=gRPC`` + - ``address=192.108.1.105`` returns endpoints that have + this address + - ``port>8080`` returns endpoints that have port number + larger than 8080 + - + + ``name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/my-service/endpoints/endpoint-c`` + returns endpoints that have name that is alphabetically + later than the string, so "endpoint-e" is returned but + "endpoint-a" is not + + - ``metadata.owner!=sd AND metadata.foo=bar`` returns + endpoints that have ``owner`` in annotation key but value + is not ``sd`` AND have key/value ``foo=bar`` + - ``doesnotexist.foo=bar`` returns an empty list. Note that + endpoint doesn't have a field called "doesnotexist". + Since the filter does not match any endpoint, it returns + no results + + For more information about filtering, see `API + Filtering `__. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + max_endpoints = proto.Field( + proto.INT32, + number=2, + ) + endpoint_filter = proto.Field( + proto.STRING, + number=3, + ) + + +class ResolveServiceResponse(proto.Message): + r"""The response message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. + + Attributes: + service (google.cloud.servicedirectory_v1beta1.types.Service): + + """ + + service = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_service.Service, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/namespace.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/namespace.py new file mode 100644 index 00000000..7e6d6d0c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/namespace.py @@ -0,0 +1,73 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.servicedirectory.v1beta1', + manifest={ + 'Namespace', + }, +) + + +class Namespace(proto.Message): + r"""A container for + [services][google.cloud.servicedirectory.v1beta1.Service]. + Namespaces allow administrators to group services together and + define permissions for a collection of services. + + Attributes: + name (str): + Immutable. The resource name for the namespace in the format + ``projects/*/locations/*/namespaces/*``. + labels (Sequence[google.cloud.servicedirectory_v1beta1.types.Namespace.LabelsEntry]): + Optional. Resource labels associated with + this namespace. No more than 64 user labels can + be associated with a given resource. Label keys + and values can be no longer than 63 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the namespace + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the namespace + was last updated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/registration_service.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/registration_service.py new file mode 100644 index 00000000..4a5d7f32 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/registration_service.py @@ -0,0 +1,675 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.servicedirectory.v1beta1', + manifest={ + 'CreateNamespaceRequest', + 'ListNamespacesRequest', + 'ListNamespacesResponse', + 'GetNamespaceRequest', + 'UpdateNamespaceRequest', + 'DeleteNamespaceRequest', + 'CreateServiceRequest', + 'ListServicesRequest', + 'ListServicesResponse', + 'GetServiceRequest', + 'UpdateServiceRequest', + 'DeleteServiceRequest', + 'CreateEndpointRequest', + 'ListEndpointsRequest', + 'ListEndpointsResponse', + 'GetEndpointRequest', + 'UpdateEndpointRequest', + 'DeleteEndpointRequest', + }, +) + + +class CreateNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateNamespace]. + + Attributes: + parent (str): + Required. The resource name of the project + and location the namespace will be created in. + namespace_id (str): + Required. The Resource ID must be 1-63 characters long, and + comply with RFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + namespace (google.cloud.servicedirectory_v1beta1.types.Namespace): + Required. A namespace with initial fields + set. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + namespace_id = proto.Field( + proto.STRING, + number=2, + ) + namespace = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_namespace.Namespace, + ) + + +class ListNamespacesRequest(proto.Message): + r"""The request message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. + + Attributes: + parent (str): + Required. The resource name of the project + and location whose namespaces you'd like to + list. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to list results by. + + General ``filter`` string syntax: + `` ()`` + + - ```` can be ``name`` or ``labels.`` for map + field + - ```` can be ``<``, ``>``, ``<=``, ``>=``, + ``!=``, ``=``, ``:``. Of which ``:`` means ``HAS``, and + is roughly the same as ``=`` + - ```` must be the same data type as field + - ```` can be ``AND``, ``OR``, ``NOT`` + + Examples of valid filters: + + - ``labels.owner`` returns namespaces that have a label + with the key ``owner``, this is the same as + ``labels:owner`` + - ``labels.owner=sd`` returns namespaces that have + key/value ``owner=sd`` + - ``name>projects/my-project/locations/us-east1/namespaces/namespace-c`` + returns namespaces that have name that is alphabetically + later than the string, so "namespace-e" is returned but + "namespace-a" is not + - ``labels.owner!=sd AND labels.foo=bar`` returns + namespaces that have ``owner`` in label key but value is + not ``sd`` AND have key/value ``foo=bar`` + - ``doesnotexist.foo=bar`` returns an empty list. Note that + namespace doesn't have a field called "doesnotexist". + Since the filter does not match any namespaces, it + returns no results + + For more information about filtering, see `API + Filtering `__. + order_by (str): + Optional. The order to list results by. + + General ``order_by`` string syntax: + `` () (,)`` + + - ```` allows value: ``name`` + - ```` ascending or descending order by + ````. If this is left blank, ``asc`` is used + + Note that an empty ``order_by`` string results in default + order, which is order by ``name`` in ascending order. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class ListNamespacesResponse(proto.Message): + r"""The response message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. + + Attributes: + namespaces (Sequence[google.cloud.servicedirectory_v1beta1.types.Namespace]): + The list of namespaces. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + namespaces = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_namespace.Namespace, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.GetNamespace]. + + Attributes: + name (str): + Required. The name of the namespace to + retrieve. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateNamespace]. + + Attributes: + namespace (google.cloud.servicedirectory_v1beta1.types.Namespace): + Required. The updated namespace. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + namespace = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_namespace.Namespace, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteNamespace]. + + Attributes: + name (str): + Required. The name of the namespace to + delete. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.CreateService][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateService]. + + Attributes: + parent (str): + Required. The resource name of the namespace + this service will belong to. + service_id (str): + Required. The Resource ID must be 1-63 characters long, and + comply with RFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + service (google.cloud.servicedirectory_v1beta1.types.Service): + Required. A service with initial fields set. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + service_id = proto.Field( + proto.STRING, + number=2, + ) + service = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_service.Service, + ) + + +class ListServicesRequest(proto.Message): + r"""The request message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. + + Attributes: + parent (str): + Required. The resource name of the namespace + whose services you'd like to list. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to list results by. + + General ``filter`` string syntax: + `` ()`` + + - ```` can be ``name`` or ``metadata.`` for map + field + - ```` can be ``<``, ``>``, ``<=``, ``>=``, + ``!=``, ``=``, ``:``. Of which ``:`` means ``HAS``, and + is roughly the same as ``=`` + - ```` must be the same data type as field + - ```` can be ``AND``, ``OR``, ``NOT`` + + Examples of valid filters: + + - ``metadata.owner`` returns services that have a metadata + with the key ``owner``, this is the same as + ``metadata:owner`` + - ``metadata.protocol=gRPC`` returns services that have + key/value ``protocol=gRPC`` + - + + ``name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/service-c`` + returns services that have name that is alphabetically later + than the string, so "service-e" is returned but "service-a" + is not + + - ``metadata.owner!=sd AND metadata.foo=bar`` returns + services that have ``owner`` in metadata key but value is + not ``sd`` AND have key/value ``foo=bar`` + - ``doesnotexist.foo=bar`` returns an empty list. Note that + service doesn't have a field called "doesnotexist". Since + the filter does not match any services, it returns no + results + + For more information about filtering, see `API + Filtering `__. + order_by (str): + Optional. The order to list results by. + + General ``order_by`` string syntax: + `` () (,)`` + + - ```` allows value: ``name`` + - ```` ascending or descending order by + ````. If this is left blank, ``asc`` is used + + Note that an empty ``order_by`` string results in default + order, which is order by ``name`` in ascending order. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class ListServicesResponse(proto.Message): + r"""The response message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. + + Attributes: + services (Sequence[google.cloud.servicedirectory_v1beta1.types.Service]): + The list of services. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + services = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_service.Service, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.GetService][google.cloud.servicedirectory.v1beta1.RegistrationService.GetService]. + This should not be used for looking up a service. Insead, use the + ``resolve`` method as it contains all endpoints and associated + metadata. + + Attributes: + name (str): + Required. The name of the service to get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.UpdateService][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateService]. + + Attributes: + service (google.cloud.servicedirectory_v1beta1.types.Service): + Required. The updated service. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + service = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_service.Service, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.DeleteService][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteService]. + + Attributes: + name (str): + Required. The name of the service to delete. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateEndpoint]. + + Attributes: + parent (str): + Required. The resource name of the service + that this endpoint provides. + endpoint_id (str): + Required. The Resource ID must be 1-63 characters long, and + comply with RFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + endpoint (google.cloud.servicedirectory_v1beta1.types.Endpoint): + Required. A endpoint with initial fields set. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + endpoint_id = proto.Field( + proto.STRING, + number=2, + ) + endpoint = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_endpoint.Endpoint, + ) + + +class ListEndpointsRequest(proto.Message): + r"""The request message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. + + Attributes: + parent (str): + Required. The resource name of the service + whose endpoints you'd like to list. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to list results by. + + General ``filter`` string syntax: + `` ()`` + + - ```` can be ``name``, ``address``, ``port``, or + ``metadata.`` for map field + - ```` can be ``<``, ``>``, ``<=``, ``>=``, + ``!=``, ``=``, ``:``. Of which ``:`` means ``HAS``, and + is roughly the same as ``=`` + - ```` must be the same data type as field + - ```` can be ``AND``, ``OR``, ``NOT`` + + Examples of valid filters: + + - ``metadata.owner`` returns endpoints that have a metadata + with the key ``owner``, this is the same as + ``metadata:owner`` + - ``metadata.protocol=gRPC`` returns endpoints that have + key/value ``protocol=gRPC`` + - ``address=192.108.1.105`` returns endpoints that have + this address + - ``port>8080`` returns endpoints that have port number + larger than 8080 + - + + ``name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/my-service/endpoints/endpoint-c`` + returns endpoints that have name that is alphabetically + later than the string, so "endpoint-e" is returned but + "endpoint-a" is not + + - ``metadata.owner!=sd AND metadata.foo=bar`` returns + endpoints that have ``owner`` in metadata key but value + is not ``sd`` AND have key/value ``foo=bar`` + - ``doesnotexist.foo=bar`` returns an empty list. Note that + endpoint doesn't have a field called "doesnotexist". + Since the filter does not match any endpoints, it returns + no results + + For more information about filtering, see `API + Filtering `__. + order_by (str): + Optional. The order to list results by. + + General ``order_by`` string syntax: + `` () (,)`` + + - ```` allows values: ``name``, ``address``, + ``port`` + - ```` ascending or descending order by + ````. If this is left blank, ``asc`` is used + + Note that an empty ``order_by`` string results in default + order, which is order by ``name`` in ascending order. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEndpointsResponse(proto.Message): + r"""The response message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. + + Attributes: + endpoints (Sequence[google.cloud.servicedirectory_v1beta1.types.Endpoint]): + The list of endpoints. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + endpoints = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_endpoint.Endpoint, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.GetEndpoint]. + This should not be used to lookup endpoints at runtime. Instead, use + the ``resolve`` method. + + Attributes: + name (str): + Required. The name of the endpoint to get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateEndpoint]. + + Attributes: + endpoint (google.cloud.servicedirectory_v1beta1.types.Endpoint): + Required. The updated endpoint. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + endpoint = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_endpoint.Endpoint, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteEndpoint]. + + Attributes: + name (str): + Required. The name of the endpoint to delete. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/service.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/service.py new file mode 100644 index 00000000..efa98fbe --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/service.py @@ -0,0 +1,111 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import endpoint +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.servicedirectory.v1beta1', + manifest={ + 'Service', + }, +) + + +class Service(proto.Message): + r"""An individual service. A service contains a name and optional + metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] can be + added to it. + + Attributes: + name (str): + Immutable. The resource name for the service in the format + ``projects/*/locations/*/namespaces/*/services/*``. + metadata (Sequence[google.cloud.servicedirectory_v1beta1.types.Service.MetadataEntry]): + Optional. Metadata for the service. This data can be + consumed by service clients. + + Restrictions: + + - The entire metadata dictionary may contain up to 2000 + characters, spread accoss all key-value pairs. Metadata + that goes beyond this limit are rejected + - Valid metadata keys have two segments: an optional prefix + and name, separated by a slash (/). The name segment is + required and must be 63 characters or less, beginning and + ending with an alphanumeric character ([a-z0-9A-Z]) with + dashes (-), underscores (_), dots (.), and alphanumerics + between. The prefix is optional. If specified, the prefix + must be a DNS subdomain: a series of DNS labels separated + by dots (.), not longer than 253 characters in total, + followed by a slash (/). Metadata that fails to meet + these requirements are rejected + - The ``(*.)google.com/`` and ``(*.)googleapis.com/`` + prefixes are reserved for system metadata managed by + Service Directory. If the user tries to write to these + keyspaces, those entries are silently ignored by the + system + + Note: This field is equivalent to the ``annotations`` field + in the v1 API. They have the same syntax and read/write to + the same location in Service Directory. + endpoints (Sequence[google.cloud.servicedirectory_v1beta1.types.Endpoint]): + Output only. Endpoints associated with this service. + Returned on + [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. + Control plane clients should use + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the service + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the service + was last updated. Note: endpoints being + created/deleted/updated within the service are + not considered service updates for the purpose + of this timestamp. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + endpoints = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=endpoint.Endpoint, + ) + create_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py new file mode 100644 index 00000000..f02a62c6 --- /dev/null +++ b/owl-bot-staging/v1beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/servicedirectory_v1beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + '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='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1beta1/scripts/fixup_servicedirectory_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_servicedirectory_v1beta1_keywords.py new file mode 100644 index 00000000..892e98cf --- /dev/null +++ b/owl-bot-staging/v1beta1/scripts/fixup_servicedirectory_v1beta1_keywords.py @@ -0,0 +1,194 @@ +#! /usr/bin/env python3 +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 servicedirectoryCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_endpoint': ('parent', 'endpoint_id', 'endpoint', ), + 'create_namespace': ('parent', 'namespace_id', 'namespace', ), + 'create_service': ('parent', 'service_id', 'service', ), + 'delete_endpoint': ('name', ), + 'delete_namespace': ('name', ), + 'delete_service': ('name', ), + 'get_endpoint': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_namespace': ('name', ), + 'get_service': ('name', ), + 'list_endpoints': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_namespaces': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_services': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'resolve_service': ('name', 'max_endpoints', 'endpoint_filter', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_endpoint': ('endpoint', 'update_mask', ), + 'update_namespace': ('namespace', 'update_mask', ), + 'update_service': ('service', 'update_mask', ), + } + + 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=servicedirectoryCallTransformer(), +): + """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 servicedirectory 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py new file mode 100644 index 00000000..0aacc848 --- /dev/null +++ b/owl-bot-staging/v1beta1/setup.py @@ -0,0 +1,54 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 setuptools # type: ignore + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-service-directory', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py new file mode 100644 index 00000000..7caa65da --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py @@ -0,0 +1,1176 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +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 path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicedirectory_v1beta1.services.lookup_service import LookupServiceAsyncClient +from google.cloud.servicedirectory_v1beta1.services.lookup_service import LookupServiceClient +from google.cloud.servicedirectory_v1beta1.services.lookup_service import transports +from google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.servicedirectory_v1beta1.types import lookup_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert LookupServiceClient._get_default_mtls_endpoint(None) is None + assert LookupServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LookupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LookupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LookupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LookupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + LookupServiceClient, + LookupServiceAsyncClient, +]) +def test_lookup_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.LookupServiceGrpcTransport, "grpc"), + (transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_lookup_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", [ + LookupServiceClient, + LookupServiceAsyncClient, +]) +def test_lookup_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +def test_lookup_service_client_get_transport_class(): + transport = LookupServiceClient.get_transport_class() + available_transports = [ + transports.LookupServiceGrpcTransport, + ] + assert transport in available_transports + + transport = LookupServiceClient.get_transport_class("grpc") + assert transport == transports.LookupServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(LookupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceClient)) +@mock.patch.object(LookupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceAsyncClient)) +def test_lookup_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(LookupServiceClient, '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(LookupServiceClient, '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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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() + 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "true"), + (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "false"), + (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(LookupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceClient)) +@mock.patch.object(LookupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_lookup_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_lookup_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_lookup_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_lookup_service_client_client_options_from_dict(): + with mock.patch('google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LookupServiceClient( + 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, + ) + + +def test_resolve_service(transport: str = 'grpc', request_type=lookup_service.ResolveServiceRequest): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lookup_service.ResolveServiceResponse( + ) + response = client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == lookup_service.ResolveServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, lookup_service.ResolveServiceResponse) + + +def test_resolve_service_from_dict(): + test_resolve_service(request_type=dict) + + +def test_resolve_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_service), + '__call__') as call: + client.resolve_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lookup_service.ResolveServiceRequest() + + +@pytest.mark.asyncio +async def test_resolve_service_async(transport: str = 'grpc_asyncio', request_type=lookup_service.ResolveServiceRequest): + client = LookupServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lookup_service.ResolveServiceResponse( + )) + response = await client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == lookup_service.ResolveServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, lookup_service.ResolveServiceResponse) + + +@pytest.mark.asyncio +async def test_resolve_service_async_from_dict(): + await test_resolve_service_async(request_type=dict) + + +def test_resolve_service_field_headers(): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lookup_service.ResolveServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_service), + '__call__') as call: + call.return_value = lookup_service.ResolveServiceResponse() + client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_resolve_service_field_headers_async(): + client = LookupServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lookup_service.ResolveServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lookup_service.ResolveServiceResponse()) + await client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LookupServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LookupServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, +]) +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_grpc_default(): + # A client should use the gRPC transport by default. + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LookupServiceGrpcTransport, + ) + +def test_lookup_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LookupServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_lookup_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LookupServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'resolve_service', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +@requires_google_auth_gte_1_25_0 +def test_lookup_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.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LookupServiceTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_lookup_service_base_transport_with_credentials_file_old_google_auth(): + # 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.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LookupServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_lookup_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.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LookupServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_lookup_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) + LookupServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_lookup_service_auth_adc_old_google_auth(): + # 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) + LookupServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_lookup_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.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_lookup_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LookupServiceGrpcTransport, grpc_helpers), + (transports.LookupServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_lookup_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( + "servicedirectory.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="servicedirectory.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) +def test_lookup_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_lookup_service_host_no_port(): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com'), + ) + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +def test_lookup_service_host_with_port(): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com:8000'), + ) + assert client.transport._host == 'servicedirectory.googleapis.com:8000' + +def test_lookup_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LookupServiceGrpcTransport( + 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_lookup_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LookupServiceGrpcAsyncIOTransport( + 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.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) +def test_lookup_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.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) +def test_lookup_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_endpoint_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + endpoint = "oyster" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) + actual = LookupServiceClient.endpoint_path(project, location, namespace, service, endpoint) + assert expected == actual + + +def test_parse_endpoint_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "namespace": "mussel", + "service": "winkle", + "endpoint": "nautilus", + } + path = LookupServiceClient.endpoint_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_endpoint_path(path) + assert expected == actual + +def test_network_path(): + project = "scallop" + network = "abalone" + expected = "projects/{project}/locations/global/networks/{network}".format(project=project, network=network, ) + actual = LookupServiceClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "squid", + "network": "clam", + } + path = LookupServiceClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_network_path(path) + assert expected == actual + +def test_service_path(): + project = "whelk" + location = "octopus" + namespace = "oyster" + service = "nudibranch" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + actual = LookupServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "namespace": "winkle", + "service": "nautilus", + } + path = LookupServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LookupServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = LookupServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = LookupServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = LookupServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LookupServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = LookupServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = LookupServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = LookupServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = LookupServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = LookupServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.LookupServiceTransport, '_prep_wrapped_messages') as prep: + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LookupServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = LookupServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = LookupServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = LookupServiceClient( + 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() diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py new file mode 100644 index 00000000..7aa0ac71 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py @@ -0,0 +1,5686 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +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 path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicedirectory_v1beta1.services.registration_service import RegistrationServiceAsyncClient +from google.cloud.servicedirectory_v1beta1.services.registration_service import RegistrationServiceClient +from google.cloud.servicedirectory_v1beta1.services.registration_service import pagers +from google.cloud.servicedirectory_v1beta1.services.registration_service import transports +from google.cloud.servicedirectory_v1beta1.services.registration_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.servicedirectory_v1beta1.types import endpoint +from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace +from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1beta1.types import registration_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service +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.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RegistrationServiceClient._get_default_mtls_endpoint(None) is None + assert RegistrationServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RegistrationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RegistrationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RegistrationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RegistrationServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + RegistrationServiceClient, + RegistrationServiceAsyncClient, +]) +def test_registration_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RegistrationServiceGrpcTransport, "grpc"), + (transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_registration_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", [ + RegistrationServiceClient, + RegistrationServiceAsyncClient, +]) +def test_registration_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +def test_registration_service_client_get_transport_class(): + transport = RegistrationServiceClient.get_transport_class() + available_transports = [ + transports.RegistrationServiceGrpcTransport, + ] + assert transport in available_transports + + transport = RegistrationServiceClient.get_transport_class("grpc") + assert transport == transports.RegistrationServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), + (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(RegistrationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceClient)) +@mock.patch.object(RegistrationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceAsyncClient)) +def test_registration_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(RegistrationServiceClient, '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(RegistrationServiceClient, '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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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() + 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc", "true"), + (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc", "false"), + (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(RegistrationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceClient)) +@mock.patch.object(RegistrationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_registration_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), + (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_registration_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), + (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_registration_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_registration_service_client_client_options_from_dict(): + with mock.patch('google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RegistrationServiceClient( + 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, + ) + + +def test_create_namespace(transport: str = 'grpc', request_type=registration_service.CreateNamespaceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace( + name='name_value', + ) + response = client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + assert response.name == 'name_value' + + +def test_create_namespace_from_dict(): + test_create_namespace(request_type=dict) + + +def test_create_namespace_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_namespace), + '__call__') as call: + client.create_namespace() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateNamespaceRequest() + + +@pytest.mark.asyncio +async def test_create_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateNamespaceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace( + name='name_value', + )) + response = await client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_namespace_async_from_dict(): + await test_create_namespace_async(request_type=dict) + + +def test_create_namespace_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateNamespaceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_namespace), + '__call__') as call: + call.return_value = gcs_namespace.Namespace() + client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateNamespaceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_namespace), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) + await client.create_namespace(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_namespace_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_namespace( + parent='parent_value', + namespace=gcs_namespace.Namespace(name='name_value'), + namespace_id='namespace_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].namespace == gcs_namespace.Namespace(name='name_value') + assert args[0].namespace_id == 'namespace_id_value' + + +def test_create_namespace_flattened_error(): + client = RegistrationServiceClient( + 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_namespace( + registration_service.CreateNamespaceRequest(), + parent='parent_value', + namespace=gcs_namespace.Namespace(name='name_value'), + namespace_id='namespace_id_value', + ) + + +@pytest.mark.asyncio +async def test_create_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_namespace( + parent='parent_value', + namespace=gcs_namespace.Namespace(name='name_value'), + namespace_id='namespace_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].namespace == gcs_namespace.Namespace(name='name_value') + assert args[0].namespace_id == 'namespace_id_value' + + +@pytest.mark.asyncio +async def test_create_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_namespace( + registration_service.CreateNamespaceRequest(), + parent='parent_value', + namespace=gcs_namespace.Namespace(name='name_value'), + namespace_id='namespace_id_value', + ) + + +def test_list_namespaces(transport: str = 'grpc', request_type=registration_service.ListNamespacesRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListNamespacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNamespacesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_namespaces_from_dict(): + test_list_namespaces(request_type=dict) + + +def test_list_namespaces_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + client.list_namespaces() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListNamespacesRequest() + + +@pytest.mark.asyncio +async def test_list_namespaces_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListNamespacesRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListNamespacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNamespacesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_namespaces_async_from_dict(): + await test_list_namespaces_async(request_type=dict) + + +def test_list_namespaces_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListNamespacesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + call.return_value = registration_service.ListNamespacesResponse() + client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_namespaces_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListNamespacesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse()) + await client.list_namespaces(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_namespaces_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_namespaces( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_namespaces_flattened_error(): + client = RegistrationServiceClient( + 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_namespaces( + registration_service.ListNamespacesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_namespaces_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_namespaces( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_namespaces_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_namespaces( + registration_service.ListNamespacesRequest(), + parent='parent_value', + ) + + +def test_list_namespaces_pager(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token='abc', + ), + registration_service.ListNamespacesResponse( + namespaces=[], + next_page_token='def', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + ], + next_page_token='ghi', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_namespaces(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, namespace.Namespace) + for i in results) + +def test_list_namespaces_pages(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token='abc', + ), + registration_service.ListNamespacesResponse( + namespaces=[], + next_page_token='def', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + ], + next_page_token='ghi', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + ], + ), + RuntimeError, + ) + pages = list(client.list_namespaces(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_namespaces_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token='abc', + ), + registration_service.ListNamespacesResponse( + namespaces=[], + next_page_token='def', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + ], + next_page_token='ghi', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_namespaces(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, namespace.Namespace) + for i in responses) + +@pytest.mark.asyncio +async def test_list_namespaces_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token='abc', + ), + registration_service.ListNamespacesResponse( + namespaces=[], + next_page_token='def', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + ], + next_page_token='ghi', + ), + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_namespaces(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_namespace(transport: str = 'grpc', request_type=registration_service.GetNamespaceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace( + name='name_value', + ) + response = client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, namespace.Namespace) + assert response.name == 'name_value' + + +def test_get_namespace_from_dict(): + test_get_namespace(request_type=dict) + + +def test_get_namespace_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_namespace), + '__call__') as call: + client.get_namespace() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetNamespaceRequest() + + +@pytest.mark.asyncio +async def test_get_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetNamespaceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace( + name='name_value', + )) + response = await client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, namespace.Namespace) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_namespace_async_from_dict(): + await test_get_namespace_async(request_type=dict) + + +def test_get_namespace_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetNamespaceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_namespace), + '__call__') as call: + call.return_value = namespace.Namespace() + client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetNamespaceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_namespace), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) + await client.get_namespace(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_namespace_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_namespace( + 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] + assert args[0].name == 'name_value' + + +def test_get_namespace_flattened_error(): + client = RegistrationServiceClient( + 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_namespace( + registration_service.GetNamespaceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_namespace( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_namespace( + registration_service.GetNamespaceRequest(), + name='name_value', + ) + + +def test_update_namespace(transport: str = 'grpc', request_type=registration_service.UpdateNamespaceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace( + name='name_value', + ) + response = client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + assert response.name == 'name_value' + + +def test_update_namespace_from_dict(): + test_update_namespace(request_type=dict) + + +def test_update_namespace_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_namespace), + '__call__') as call: + client.update_namespace() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateNamespaceRequest() + + +@pytest.mark.asyncio +async def test_update_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateNamespaceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace( + name='name_value', + )) + response = await client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_namespace_async_from_dict(): + await test_update_namespace_async(request_type=dict) + + +def test_update_namespace_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateNamespaceRequest() + + request.namespace.name = 'namespace.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_namespace), + '__call__') as call: + call.return_value = gcs_namespace.Namespace() + client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'namespace.name=namespace.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateNamespaceRequest() + + request.namespace.name = 'namespace.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_namespace), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) + await client.update_namespace(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', + 'namespace.name=namespace.name/value', + ) in kw['metadata'] + + +def test_update_namespace_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_namespace( + namespace=gcs_namespace.Namespace(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].namespace == gcs_namespace.Namespace(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_namespace_flattened_error(): + client = RegistrationServiceClient( + 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_namespace( + registration_service.UpdateNamespaceRequest(), + namespace=gcs_namespace.Namespace(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_namespace( + namespace=gcs_namespace.Namespace(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].namespace == gcs_namespace.Namespace(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_namespace( + registration_service.UpdateNamespaceRequest(), + namespace=gcs_namespace.Namespace(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_namespace(transport: str = 'grpc', request_type=registration_service.DeleteNamespaceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteNamespaceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_namespace_from_dict(): + test_delete_namespace(request_type=dict) + + +def test_delete_namespace_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_namespace), + '__call__') as call: + client.delete_namespace() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteNamespaceRequest() + + +@pytest.mark.asyncio +async def test_delete_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteNamespaceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteNamespaceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_namespace_async_from_dict(): + await test_delete_namespace_async(request_type=dict) + + +def test_delete_namespace_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteNamespaceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_namespace), + '__call__') as call: + call.return_value = None + client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteNamespaceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_namespace), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_namespace(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_namespace_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_namespace( + 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] + assert args[0].name == 'name_value' + + +def test_delete_namespace_flattened_error(): + client = RegistrationServiceClient( + 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_namespace( + registration_service.DeleteNamespaceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_namespace), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_namespace( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_namespace( + registration_service.DeleteNamespaceRequest(), + name='name_value', + ) + + +def test_create_service(transport: str = 'grpc', request_type=registration_service.CreateServiceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service( + name='name_value', + ) + response = client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + assert response.name == 'name_value' + + +def test_create_service_from_dict(): + test_create_service(request_type=dict) + + +def test_create_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + client.create_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateServiceRequest() + + +@pytest.mark.asyncio +async def test_create_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateServiceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service( + name='name_value', + )) + response = await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_service_async_from_dict(): + await test_create_service_async(request_type=dict) + + +def test_create_service_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateServiceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + call.return_value = gcs_service.Service() + client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateServiceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_create_service_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_service( + parent='parent_value', + service=gcs_service.Service(name='name_value'), + service_id='service_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].service == gcs_service.Service(name='name_value') + assert args[0].service_id == 'service_id_value' + + +def test_create_service_flattened_error(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_service( + registration_service.CreateServiceRequest(), + parent='parent_value', + service=gcs_service.Service(name='name_value'), + service_id='service_id_value', + ) + + +@pytest.mark.asyncio +async def test_create_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_service( + parent='parent_value', + service=gcs_service.Service(name='name_value'), + service_id='service_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].service == gcs_service.Service(name='name_value') + assert args[0].service_id == 'service_id_value' + + +@pytest.mark.asyncio +async def test_create_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_service( + registration_service.CreateServiceRequest(), + parent='parent_value', + service=gcs_service.Service(name='name_value'), + service_id='service_id_value', + ) + + +def test_list_services(transport: str = 'grpc', request_type=registration_service.ListServicesRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListServicesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_services_from_dict(): + test_list_services(request_type=dict) + + +def test_list_services_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + client.list_services() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListServicesRequest() + + +@pytest.mark.asyncio +async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListServicesRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_services_async_from_dict(): + await test_list_services_async(request_type=dict) + + +def test_list_services_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListServicesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = registration_service.ListServicesResponse() + client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_services_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListServicesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse()) + await client.list_services(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_services_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListServicesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_services( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_services_flattened_error(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_services( + registration_service.ListServicesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_services_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListServicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_services( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_services_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_services( + registration_service.ListServicesRequest(), + parent='parent_value', + ) + + +def test_list_services_pager(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + registration_service.ListServicesResponse( + services=[], + next_page_token='def', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_services(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, service.Service) + for i in results) + +def test_list_services_pages(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + registration_service.ListServicesResponse( + services=[], + next_page_token='def', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + pages = list(client.list_services(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_services_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + registration_service.ListServicesResponse( + services=[], + next_page_token='def', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_services(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, service.Service) + for i in responses) + +@pytest.mark.asyncio +async def test_list_services_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + registration_service.ListServicesResponse( + services=[], + next_page_token='def', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + registration_service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_services(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_service(transport: str = 'grpc', request_type=registration_service.GetServiceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.Service( + name='name_value', + ) + response = client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + assert response.name == 'name_value' + + +def test_get_service_from_dict(): + test_get_service(request_type=dict) + + +def test_get_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + client.get_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetServiceRequest() + + +@pytest.mark.asyncio +async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetServiceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.Service( + name='name_value', + )) + response = await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_service_async_from_dict(): + await test_get_service_async(request_type=dict) + + +def test_get_service_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = service.Service() + client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) + await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_service_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.Service() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_service_flattened_error(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_service( + registration_service.GetServiceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_service( + registration_service.GetServiceRequest(), + name='name_value', + ) + + +def test_update_service(transport: str = 'grpc', request_type=registration_service.UpdateServiceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service( + name='name_value', + ) + response = client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + assert response.name == 'name_value' + + +def test_update_service_from_dict(): + test_update_service(request_type=dict) + + +def test_update_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + client.update_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateServiceRequest() + + +@pytest.mark.asyncio +async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateServiceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service( + name='name_value', + )) + response = await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_service_async_from_dict(): + await test_update_service_async(request_type=dict) + + +def test_update_service_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateServiceRequest() + + request.service.name = 'service.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = gcs_service.Service() + client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service.name=service.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateServiceRequest() + + request.service.name = 'service.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service.name=service.name/value', + ) in kw['metadata'] + + +def test_update_service_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_service( + service=gcs_service.Service(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].service == gcs_service.Service(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_service_flattened_error(): + client = RegistrationServiceClient( + 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_service( + registration_service.UpdateServiceRequest(), + service=gcs_service.Service(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_service( + service=gcs_service.Service(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].service == gcs_service.Service(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_service( + registration_service.UpdateServiceRequest(), + service=gcs_service.Service(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_service(transport: str = 'grpc', request_type=registration_service.DeleteServiceRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_service_from_dict(): + test_delete_service(request_type=dict) + + +def test_delete_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + client.delete_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteServiceRequest() + + +@pytest.mark.asyncio +async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteServiceRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_service_async_from_dict(): + await test_delete_service_async(request_type=dict) + + +def test_delete_service_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = None + client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_service_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_delete_service_flattened_error(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_service( + registration_service.DeleteServiceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_service( + registration_service.DeleteServiceRequest(), + name='name_value', + ) + + +def test_create_endpoint(transport: str = 'grpc', request_type=registration_service.CreateEndpointRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + network='network_value', + ) + response = client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + assert response.network == 'network_value' + + +def test_create_endpoint_from_dict(): + test_create_endpoint(request_type=dict) + + +def test_create_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint), + '__call__') as call: + client.create_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateEndpointRequest() + + +@pytest.mark.asyncio +async def test_create_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateEndpointRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + network='network_value', + )) + response = await client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.CreateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + assert response.network == 'network_value' + + +@pytest.mark.asyncio +async def test_create_endpoint_async_from_dict(): + await test_create_endpoint_async(request_type=dict) + + +def test_create_endpoint_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateEndpointRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint), + '__call__') as call: + call.return_value = gcs_endpoint.Endpoint() + client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.CreateEndpointRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) + await client.create_endpoint(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_endpoint_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_endpoint( + parent='parent_value', + endpoint=gcs_endpoint.Endpoint(name='name_value'), + endpoint_id='endpoint_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') + assert args[0].endpoint_id == 'endpoint_id_value' + + +def test_create_endpoint_flattened_error(): + client = RegistrationServiceClient( + 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_endpoint( + registration_service.CreateEndpointRequest(), + parent='parent_value', + endpoint=gcs_endpoint.Endpoint(name='name_value'), + endpoint_id='endpoint_id_value', + ) + + +@pytest.mark.asyncio +async def test_create_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_endpoint( + parent='parent_value', + endpoint=gcs_endpoint.Endpoint(name='name_value'), + endpoint_id='endpoint_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') + assert args[0].endpoint_id == 'endpoint_id_value' + + +@pytest.mark.asyncio +async def test_create_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_endpoint( + registration_service.CreateEndpointRequest(), + parent='parent_value', + endpoint=gcs_endpoint.Endpoint(name='name_value'), + endpoint_id='endpoint_id_value', + ) + + +def test_list_endpoints(transport: str = 'grpc', request_type=registration_service.ListEndpointsRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListEndpointsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_endpoints_from_dict(): + test_list_endpoints(request_type=dict) + + +def test_list_endpoints_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + client.list_endpoints() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListEndpointsRequest() + + +@pytest.mark.asyncio +async def test_list_endpoints_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListEndpointsRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.ListEndpointsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_endpoints_async_from_dict(): + await test_list_endpoints_async(request_type=dict) + + +def test_list_endpoints_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListEndpointsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + call.return_value = registration_service.ListEndpointsResponse() + client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_endpoints_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.ListEndpointsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse()) + await client.list_endpoints(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_endpoints_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_endpoints( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_endpoints_flattened_error(): + client = RegistrationServiceClient( + 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_endpoints( + registration_service.ListEndpointsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_endpoints_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_endpoints( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_endpoints_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_endpoints( + registration_service.ListEndpointsRequest(), + parent='parent_value', + ) + + +def test_list_endpoints_pager(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token='abc', + ), + registration_service.ListEndpointsResponse( + endpoints=[], + next_page_token='def', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + ], + next_page_token='ghi', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_endpoints(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, endpoint.Endpoint) + for i in results) + +def test_list_endpoints_pages(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token='abc', + ), + registration_service.ListEndpointsResponse( + endpoints=[], + next_page_token='def', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + ], + next_page_token='ghi', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + ), + RuntimeError, + ) + pages = list(client.list_endpoints(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_endpoints_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token='abc', + ), + registration_service.ListEndpointsResponse( + endpoints=[], + next_page_token='def', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + ], + next_page_token='ghi', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_endpoints(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, endpoint.Endpoint) + for i in responses) + +@pytest.mark.asyncio +async def test_list_endpoints_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token='abc', + ), + registration_service.ListEndpointsResponse( + endpoints=[], + next_page_token='def', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + ], + next_page_token='ghi', + ), + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_endpoints(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_endpoint(transport: str = 'grpc', request_type=registration_service.GetEndpointRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + network='network_value', + ) + response = client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + assert response.network == 'network_value' + + +def test_get_endpoint_from_dict(): + test_get_endpoint(request_type=dict) + + +def test_get_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint), + '__call__') as call: + client.get_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetEndpointRequest() + + +@pytest.mark.asyncio +async def test_get_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetEndpointRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + network='network_value', + )) + response = await client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.GetEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + assert response.network == 'network_value' + + +@pytest.mark.asyncio +async def test_get_endpoint_async_from_dict(): + await test_get_endpoint_async(request_type=dict) + + +def test_get_endpoint_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetEndpointRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint), + '__call__') as call: + call.return_value = endpoint.Endpoint() + client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.GetEndpointRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) + await client.get_endpoint(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_endpoint_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_endpoint( + 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] + assert args[0].name == 'name_value' + + +def test_get_endpoint_flattened_error(): + client = RegistrationServiceClient( + 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_endpoint( + registration_service.GetEndpointRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_endpoint( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_endpoint( + registration_service.GetEndpointRequest(), + name='name_value', + ) + + +def test_update_endpoint(transport: str = 'grpc', request_type=registration_service.UpdateEndpointRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + network='network_value', + ) + response = client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + assert response.network == 'network_value' + + +def test_update_endpoint_from_dict(): + test_update_endpoint(request_type=dict) + + +def test_update_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint), + '__call__') as call: + client.update_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateEndpointRequest() + + +@pytest.mark.asyncio +async def test_update_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateEndpointRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint( + name='name_value', + address='address_value', + port=453, + network='network_value', + )) + response = await client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.UpdateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + assert response.name == 'name_value' + assert response.address == 'address_value' + assert response.port == 453 + assert response.network == 'network_value' + + +@pytest.mark.asyncio +async def test_update_endpoint_async_from_dict(): + await test_update_endpoint_async(request_type=dict) + + +def test_update_endpoint_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateEndpointRequest() + + request.endpoint.name = 'endpoint.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint), + '__call__') as call: + call.return_value = gcs_endpoint.Endpoint() + client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'endpoint.name=endpoint.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.UpdateEndpointRequest() + + request.endpoint.name = 'endpoint.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) + await client.update_endpoint(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', + 'endpoint.name=endpoint.name/value', + ) in kw['metadata'] + + +def test_update_endpoint_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_endpoint( + endpoint=gcs_endpoint.Endpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_endpoint_flattened_error(): + client = RegistrationServiceClient( + 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_endpoint( + registration_service.UpdateEndpointRequest(), + endpoint=gcs_endpoint.Endpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_endpoint( + endpoint=gcs_endpoint.Endpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_endpoint( + registration_service.UpdateEndpointRequest(), + endpoint=gcs_endpoint.Endpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_endpoint(transport: str = 'grpc', request_type=registration_service.DeleteEndpointRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteEndpointRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_endpoint_from_dict(): + test_delete_endpoint(request_type=dict) + + +def test_delete_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint), + '__call__') as call: + client.delete_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteEndpointRequest() + + +@pytest.mark.asyncio +async def test_delete_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteEndpointRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registration_service.DeleteEndpointRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_endpoint_async_from_dict(): + await test_delete_endpoint_async(request_type=dict) + + +def test_delete_endpoint_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteEndpointRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint), + '__call__') as call: + call.return_value = None + client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = registration_service.DeleteEndpointRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_endpoint(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_endpoint_flattened(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_endpoint( + 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] + assert args[0].name == 'name_value' + + +def test_delete_endpoint_flattened_error(): + client = RegistrationServiceClient( + 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_endpoint( + registration_service.DeleteEndpointRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_endpoint( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_endpoint( + registration_service.DeleteEndpointRequest(), + name='name_value', + ) + + +def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + test_get_iam_policy(request_type=dict) + + +def test_get_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = RegistrationServiceClient( + 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() + + +def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + test_set_iam_policy(request_type=dict) + + +def test_set_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = RegistrationServiceClient( + 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() + + +def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + test_test_iam_permissions(request_type=dict) + + +def test_test_iam_permissions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = RegistrationServiceClient( + 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() + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegistrationServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RegistrationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, +]) +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_grpc_default(): + # A client should use the gRPC transport by default. + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RegistrationServiceGrpcTransport, + ) + +def test_registration_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegistrationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_registration_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RegistrationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_namespace', + 'list_namespaces', + 'get_namespace', + 'update_namespace', + 'delete_namespace', + 'create_service', + 'list_services', + 'get_service', + 'update_service', + 'delete_service', + 'create_endpoint', + 'list_endpoints', + 'get_endpoint', + 'update_endpoint', + 'delete_endpoint', + 'get_iam_policy', + 'set_iam_policy', + 'test_iam_permissions', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +@requires_google_auth_gte_1_25_0 +def test_registration_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.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegistrationServiceTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_registration_service_base_transport_with_credentials_file_old_google_auth(): + # 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.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegistrationServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_registration_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.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegistrationServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_registration_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) + RegistrationServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_registration_service_auth_adc_old_google_auth(): + # 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) + RegistrationServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_registration_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.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_registration_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RegistrationServiceGrpcTransport, grpc_helpers), + (transports.RegistrationServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_registration_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( + "servicedirectory.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="servicedirectory.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) +def test_registration_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_registration_service_host_no_port(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com'), + ) + assert client.transport._host == 'servicedirectory.googleapis.com:443' + + +def test_registration_service_host_with_port(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com:8000'), + ) + assert client.transport._host == 'servicedirectory.googleapis.com:8000' + +def test_registration_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegistrationServiceGrpcTransport( + 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_registration_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegistrationServiceGrpcAsyncIOTransport( + 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.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) +def test_registration_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.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) +def test_registration_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_endpoint_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + endpoint = "oyster" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) + actual = RegistrationServiceClient.endpoint_path(project, location, namespace, service, endpoint) + assert expected == actual + + +def test_parse_endpoint_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "namespace": "mussel", + "service": "winkle", + "endpoint": "nautilus", + } + path = RegistrationServiceClient.endpoint_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_endpoint_path(path) + assert expected == actual + +def test_namespace_path(): + project = "scallop" + location = "abalone" + namespace = "squid" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}".format(project=project, location=location, namespace=namespace, ) + actual = RegistrationServiceClient.namespace_path(project, location, namespace) + assert expected == actual + + +def test_parse_namespace_path(): + expected = { + "project": "clam", + "location": "whelk", + "namespace": "octopus", + } + path = RegistrationServiceClient.namespace_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_namespace_path(path) + assert expected == actual + +def test_network_path(): + project = "oyster" + network = "nudibranch" + expected = "projects/{project}/locations/global/networks/{network}".format(project=project, network=network, ) + actual = RegistrationServiceClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "cuttlefish", + "network": "mussel", + } + path = RegistrationServiceClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_network_path(path) + assert expected == actual + +def test_service_path(): + project = "winkle" + location = "nautilus" + namespace = "scallop" + service = "abalone" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + actual = RegistrationServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "squid", + "location": "clam", + "namespace": "whelk", + "service": "octopus", + } + path = RegistrationServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RegistrationServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = RegistrationServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = RegistrationServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = RegistrationServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RegistrationServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = RegistrationServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = RegistrationServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = RegistrationServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.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 = RegistrationServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = RegistrationServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RegistrationServiceTransport, '_prep_wrapped_messages') as prep: + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RegistrationServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = RegistrationServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = RegistrationServiceClient( + 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() From b4230f44a0dee9a72e6038c3523cabdff0b818fb Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 6 Oct 2021 23:04:33 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= 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 --- .../services/lookup_service/async_client.py | 6 + .../services/lookup_service/client.py | 18 +- .../lookup_service/transports/base.py | 9 + .../lookup_service/transports/grpc.py | 3 + .../lookup_service/transports/grpc_asyncio.py | 3 + .../registration_service/async_client.py | 6 + .../services/registration_service/client.py | 18 +- .../registration_service/transports/base.py | 9 + .../registration_service/transports/grpc.py | 3 + .../transports/grpc_asyncio.py | 3 + .../services/lookup_service/async_client.py | 6 + .../services/lookup_service/client.py | 18 +- .../lookup_service/transports/base.py | 9 + .../lookup_service/transports/grpc.py | 3 + .../lookup_service/transports/grpc_asyncio.py | 3 + .../registration_service/async_client.py | 6 + .../services/registration_service/client.py | 18 +- .../registration_service/transports/base.py | 9 + .../registration_service/transports/grpc.py | 3 + .../transports/grpc_asyncio.py | 3 + owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 -- owl-bot-staging/v1/docs/index.rst | 7 - .../servicedirectory_v1/lookup_service.rst | 6 - .../registration_service.rst | 10 - .../v1/docs/servicedirectory_v1/services.rst | 7 - .../v1/docs/servicedirectory_v1/types.rst | 7 - .../google/cloud/servicedirectory/__init__.py | 73 - .../v1/google/cloud/servicedirectory/py.typed | 2 - .../cloud/servicedirectory_v1/__init__.py | 74 - .../servicedirectory_v1/gapic_metadata.json | 227 - .../google/cloud/servicedirectory_v1/py.typed | 2 - .../servicedirectory_v1/services/__init__.py | 15 - .../services/lookup_service/__init__.py | 22 - .../services/lookup_service/async_client.py | 226 - .../services/lookup_service/client.py | 433 -- .../lookup_service/transports/__init__.py | 33 - .../lookup_service/transports/base.py | 177 - .../lookup_service/transports/grpc.py | 256 - .../lookup_service/transports/grpc_asyncio.py | 261 - .../services/registration_service/__init__.py | 22 - .../registration_service/async_client.py | 1736 ----- .../services/registration_service/client.py | 1948 ------ .../services/registration_service/pagers.py | 387 -- .../transports/__init__.py | 33 - .../registration_service/transports/base.py | 424 -- .../registration_service/transports/grpc.py | 724 --- .../transports/grpc_asyncio.py | 729 --- .../servicedirectory_v1/types/__init__.py | 74 - .../servicedirectory_v1/types/endpoint.py | 90 - .../types/lookup_service.py | 95 - .../servicedirectory_v1/types/namespace.py | 55 - .../types/registration_service.py | 614 -- .../servicedirectory_v1/types/service.py | 87 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../fixup_servicedirectory_v1_keywords.py | 194 - owl-bot-staging/v1/setup.py | 54 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/servicedirectory_v1/__init__.py | 16 - .../test_lookup_service.py | 1157 ---- .../test_registration_service.py | 5654 ---------------- owl-bot-staging/v1beta1/.coveragerc | 17 - owl-bot-staging/v1beta1/MANIFEST.in | 2 - owl-bot-staging/v1beta1/README.rst | 49 - owl-bot-staging/v1beta1/docs/conf.py | 376 -- owl-bot-staging/v1beta1/docs/index.rst | 7 - .../lookup_service.rst | 6 - .../registration_service.rst | 10 - .../servicedirectory_v1beta1/services.rst | 7 - .../docs/servicedirectory_v1beta1/types.rst | 7 - .../google/cloud/servicedirectory/__init__.py | 73 - .../google/cloud/servicedirectory/py.typed | 2 - .../servicedirectory_v1beta1/__init__.py | 74 - .../gapic_metadata.json | 227 - .../cloud/servicedirectory_v1beta1/py.typed | 2 - .../services/__init__.py | 15 - .../services/lookup_service/__init__.py | 22 - .../services/lookup_service/async_client.py | 229 - .../services/lookup_service/client.py | 445 -- .../lookup_service/transports/__init__.py | 33 - .../lookup_service/transports/base.py | 177 - .../lookup_service/transports/grpc.py | 257 - .../lookup_service/transports/grpc_asyncio.py | 262 - .../services/registration_service/__init__.py | 22 - .../registration_service/async_client.py | 1740 ----- .../services/registration_service/client.py | 1961 ------ .../services/registration_service/pagers.py | 387 -- .../transports/__init__.py | 33 - .../registration_service/transports/base.py | 424 -- .../registration_service/transports/grpc.py | 725 --- .../transports/grpc_asyncio.py | 730 --- .../types/__init__.py | 74 - .../types/endpoint.py | 130 - .../types/lookup_service.py | 120 - .../types/namespace.py | 73 - .../types/registration_service.py | 675 -- .../servicedirectory_v1beta1/types/service.py | 111 - owl-bot-staging/v1beta1/mypy.ini | 3 - owl-bot-staging/v1beta1/noxfile.py | 132 - ...fixup_servicedirectory_v1beta1_keywords.py | 194 - owl-bot-staging/v1beta1/setup.py | 54 - owl-bot-staging/v1beta1/tests/__init__.py | 16 - .../v1beta1/tests/unit/__init__.py | 16 - .../v1beta1/tests/unit/gapic/__init__.py | 16 - .../servicedirectory_v1beta1/__init__.py | 16 - .../test_lookup_service.py | 1176 ---- .../test_registration_service.py | 5686 ----------------- .../test_lookup_service.py | 50 + .../test_registration_service.py | 50 + .../test_lookup_service.py | 50 + .../test_registration_service.py | 50 + 116 files changed, 340 insertions(+), 33387 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/docs/servicedirectory_v1/lookup_service.rst delete mode 100644 owl-bot-staging/v1/docs/servicedirectory_v1/registration_service.rst delete mode 100644 owl-bot-staging/v1/docs/servicedirectory_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/servicedirectory_v1/types.rst delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/endpoint.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/lookup_service.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/namespace.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/registration_service.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/service.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/scripts/fixup_servicedirectory_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_registration_service.py delete mode 100644 owl-bot-staging/v1beta1/.coveragerc delete mode 100644 owl-bot-staging/v1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1beta1/README.rst delete mode 100644 owl-bot-staging/v1beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/lookup_service.rst delete mode 100644 owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/registration_service.rst delete mode 100644 owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/services.rst delete mode 100644 owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/types.rst delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory/py.typed delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/py.typed delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/endpoint.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/lookup_service.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/namespace.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/registration_service.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/service.py delete mode 100644 owl-bot-staging/v1beta1/mypy.ini delete mode 100644 owl-bot-staging/v1beta1/noxfile.py delete mode 100644 owl-bot-staging/v1beta1/scripts/fixup_servicedirectory_v1beta1_keywords.py delete mode 100644 owl-bot-staging/v1beta1/setup.py delete mode 100644 owl-bot-staging/v1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py b/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py index 501b04ca..eb1c1a25 100644 --- a/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py +++ b/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py @@ -216,6 +216,12 @@ async def resolve_service( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/client.py b/google/cloud/servicedirectory_v1/services/lookup_service/client.py index 84fc9630..37304de4 100644 --- a/google/cloud/servicedirectory_v1/services/lookup_service/client.py +++ b/google/cloud/servicedirectory_v1/services/lookup_service/client.py @@ -364,10 +364,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def resolve_service( @@ -424,6 +421,19 @@ def resolve_service( # Done; return the response. return response + def __enter__(self): + 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() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py b/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py index d66f8355..cecc9953 100644 --- a/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py +++ b/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py @@ -159,6 +159,15 @@ def _prep_wrapped_messages(self, 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 resolve_service( self, diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py b/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py index b907ccad..93eee38f 100644 --- a/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py +++ b/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py @@ -255,5 +255,8 @@ def resolve_service( ) return self._stubs["resolve_service"] + def close(self): + self.grpc_channel.close() + __all__ = ("LookupServiceGrpcTransport",) diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py b/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py index a9951d9a..36105e45 100644 --- a/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py +++ b/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py @@ -259,5 +259,8 @@ def resolve_service( ) return self._stubs["resolve_service"] + def close(self): + return self.grpc_channel.close() + __all__ = ("LookupServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/servicedirectory_v1/services/registration_service/async_client.py b/google/cloud/servicedirectory_v1/services/registration_service/async_client.py index e8384705..096d7d31 100644 --- a/google/cloud/servicedirectory_v1/services/registration_service/async_client.py +++ b/google/cloud/servicedirectory_v1/services/registration_service/async_client.py @@ -1658,6 +1658,12 @@ async def test_iam_permissions( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/servicedirectory_v1/services/registration_service/client.py b/google/cloud/servicedirectory_v1/services/registration_service/client.py index b539d340..0620761b 100644 --- a/google/cloud/servicedirectory_v1/services/registration_service/client.py +++ b/google/cloud/servicedirectory_v1/services/registration_service/client.py @@ -408,10 +408,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def create_namespace( @@ -1879,6 +1876,19 @@ def test_iam_permissions( # Done; return the response. return response + def __enter__(self): + 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() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py b/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py index e82bf235..1733f7b7 100644 --- a/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py +++ b/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py @@ -221,6 +221,15 @@ def _prep_wrapped_messages(self, 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 create_namespace( self, diff --git a/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py b/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py index c66eb8ea..295d391c 100644 --- a/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py +++ b/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py @@ -737,5 +737,8 @@ def test_iam_permissions( ) return self._stubs["test_iam_permissions"] + def close(self): + self.grpc_channel.close() + __all__ = ("RegistrationServiceGrpcTransport",) diff --git a/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py b/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py index 287b36b6..a159086b 100644 --- a/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py +++ b/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py @@ -760,5 +760,8 @@ def test_iam_permissions( ) return self._stubs["test_iam_permissions"] + def close(self): + return self.grpc_channel.close() + __all__ = ("RegistrationServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py index 1a198208..622a3ade 100644 --- a/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py @@ -219,6 +219,12 @@ async def resolve_service( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py index cb2e0426..4f0efe28 100644 --- a/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py @@ -380,10 +380,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def resolve_service( @@ -441,6 +438,19 @@ def resolve_service( # Done; return the response. return response + def __enter__(self): + 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() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py index 6cbf662c..e577c29e 100644 --- a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py @@ -159,6 +159,15 @@ def _prep_wrapped_messages(self, 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 resolve_service( self, diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py index 1e6a59e1..1a4faf02 100644 --- a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py @@ -256,5 +256,8 @@ def resolve_service( ) return self._stubs["resolve_service"] + def close(self): + self.grpc_channel.close() + __all__ = ("LookupServiceGrpcTransport",) diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py index e5987f05..6c82fd38 100644 --- a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py @@ -260,5 +260,8 @@ def resolve_service( ) return self._stubs["resolve_service"] + def close(self): + return self.grpc_channel.close() + __all__ = ("LookupServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py index 2f281b85..f12f0845 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py @@ -1662,6 +1662,12 @@ async def test_iam_permissions( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py index 38de642c..c963121e 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py @@ -426,10 +426,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def create_namespace( @@ -1897,6 +1894,19 @@ def test_iam_permissions( # Done; return the response. return response + def __enter__(self): + 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() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py index 4040e6f7..5e0dafe0 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py @@ -221,6 +221,15 @@ def _prep_wrapped_messages(self, 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 create_namespace( self, diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py index 2e0564ae..c854bfde 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py @@ -738,5 +738,8 @@ def test_iam_permissions( ) return self._stubs["test_iam_permissions"] + def close(self): + self.grpc_channel.close() + __all__ = ("RegistrationServiceGrpcTransport",) diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py index 794a84e8..16be09b5 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py @@ -761,5 +761,8 @@ def test_iam_permissions( ) return self._stubs["test_iam_permissions"] + def close(self): + return self.grpc_channel.close() + __all__ = ("RegistrationServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 078f9e0e..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/servicedirectory/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index b87a38b8..00000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/servicedirectory *.py -recursive-include google/cloud/servicedirectory_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 2a61473b..00000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Servicedirectory 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 Servicedirectory 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/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index f684689e..00000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-servicedirectory 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-servicedirectory" -copyright = u"2020, 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 = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# 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-servicedirectory-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 = [ - ( - master_doc, - "google-cloud-servicedirectory.tex", - u"google-cloud-servicedirectory 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 = [ - ( - master_doc, - "google-cloud-servicedirectory", - u"Google Cloud Servicedirectory 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 = [ - ( - master_doc, - "google-cloud-servicedirectory", - u"google-cloud-servicedirectory Documentation", - author, - "google-cloud-servicedirectory", - "GAPIC library for Google Cloud Servicedirectory 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/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index cc43e5d2..00000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - servicedirectory_v1/services - servicedirectory_v1/types diff --git a/owl-bot-staging/v1/docs/servicedirectory_v1/lookup_service.rst b/owl-bot-staging/v1/docs/servicedirectory_v1/lookup_service.rst deleted file mode 100644 index a71b7da8..00000000 --- a/owl-bot-staging/v1/docs/servicedirectory_v1/lookup_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -LookupService -------------------------------- - -.. automodule:: google.cloud.servicedirectory_v1.services.lookup_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/servicedirectory_v1/registration_service.rst b/owl-bot-staging/v1/docs/servicedirectory_v1/registration_service.rst deleted file mode 100644 index 1f8f5330..00000000 --- a/owl-bot-staging/v1/docs/servicedirectory_v1/registration_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -RegistrationService -------------------------------------- - -.. automodule:: google.cloud.servicedirectory_v1.services.registration_service - :members: - :inherited-members: - -.. automodule:: google.cloud.servicedirectory_v1.services.registration_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/servicedirectory_v1/services.rst b/owl-bot-staging/v1/docs/servicedirectory_v1/services.rst deleted file mode 100644 index be303040..00000000 --- a/owl-bot-staging/v1/docs/servicedirectory_v1/services.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Servicedirectory v1 API -================================================= -.. toctree:: - :maxdepth: 2 - - lookup_service - registration_service diff --git a/owl-bot-staging/v1/docs/servicedirectory_v1/types.rst b/owl-bot-staging/v1/docs/servicedirectory_v1/types.rst deleted file mode 100644 index 376220b5..00000000 --- a/owl-bot-staging/v1/docs/servicedirectory_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Servicedirectory v1 API -============================================== - -.. automodule:: google.cloud.servicedirectory_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory/__init__.py deleted file mode 100644 index 15bed353..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory/__init__.py +++ /dev/null @@ -1,73 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.servicedirectory_v1.services.lookup_service.client import LookupServiceClient -from google.cloud.servicedirectory_v1.services.lookup_service.async_client import LookupServiceAsyncClient -from google.cloud.servicedirectory_v1.services.registration_service.client import RegistrationServiceClient -from google.cloud.servicedirectory_v1.services.registration_service.async_client import RegistrationServiceAsyncClient - -from google.cloud.servicedirectory_v1.types.endpoint import Endpoint -from google.cloud.servicedirectory_v1.types.lookup_service import ResolveServiceRequest -from google.cloud.servicedirectory_v1.types.lookup_service import ResolveServiceResponse -from google.cloud.servicedirectory_v1.types.namespace import Namespace -from google.cloud.servicedirectory_v1.types.registration_service import CreateEndpointRequest -from google.cloud.servicedirectory_v1.types.registration_service import CreateNamespaceRequest -from google.cloud.servicedirectory_v1.types.registration_service import CreateServiceRequest -from google.cloud.servicedirectory_v1.types.registration_service import DeleteEndpointRequest -from google.cloud.servicedirectory_v1.types.registration_service import DeleteNamespaceRequest -from google.cloud.servicedirectory_v1.types.registration_service import DeleteServiceRequest -from google.cloud.servicedirectory_v1.types.registration_service import GetEndpointRequest -from google.cloud.servicedirectory_v1.types.registration_service import GetNamespaceRequest -from google.cloud.servicedirectory_v1.types.registration_service import GetServiceRequest -from google.cloud.servicedirectory_v1.types.registration_service import ListEndpointsRequest -from google.cloud.servicedirectory_v1.types.registration_service import ListEndpointsResponse -from google.cloud.servicedirectory_v1.types.registration_service import ListNamespacesRequest -from google.cloud.servicedirectory_v1.types.registration_service import ListNamespacesResponse -from google.cloud.servicedirectory_v1.types.registration_service import ListServicesRequest -from google.cloud.servicedirectory_v1.types.registration_service import ListServicesResponse -from google.cloud.servicedirectory_v1.types.registration_service import UpdateEndpointRequest -from google.cloud.servicedirectory_v1.types.registration_service import UpdateNamespaceRequest -from google.cloud.servicedirectory_v1.types.registration_service import UpdateServiceRequest -from google.cloud.servicedirectory_v1.types.service import Service - -__all__ = ('LookupServiceClient', - 'LookupServiceAsyncClient', - 'RegistrationServiceClient', - 'RegistrationServiceAsyncClient', - 'Endpoint', - 'ResolveServiceRequest', - 'ResolveServiceResponse', - 'Namespace', - 'CreateEndpointRequest', - 'CreateNamespaceRequest', - 'CreateServiceRequest', - 'DeleteEndpointRequest', - 'DeleteNamespaceRequest', - 'DeleteServiceRequest', - 'GetEndpointRequest', - 'GetNamespaceRequest', - 'GetServiceRequest', - 'ListEndpointsRequest', - 'ListEndpointsResponse', - 'ListNamespacesRequest', - 'ListNamespacesResponse', - 'ListServicesRequest', - 'ListServicesResponse', - 'UpdateEndpointRequest', - 'UpdateNamespaceRequest', - 'UpdateServiceRequest', - 'Service', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory/py.typed b/owl-bot-staging/v1/google/cloud/servicedirectory/py.typed deleted file mode 100644 index 6790e24b..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-servicedirectory package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/__init__.py deleted file mode 100644 index 9160262b..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/__init__.py +++ /dev/null @@ -1,74 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .services.lookup_service import LookupServiceClient -from .services.lookup_service import LookupServiceAsyncClient -from .services.registration_service import RegistrationServiceClient -from .services.registration_service import RegistrationServiceAsyncClient - -from .types.endpoint import Endpoint -from .types.lookup_service import ResolveServiceRequest -from .types.lookup_service import ResolveServiceResponse -from .types.namespace import Namespace -from .types.registration_service import CreateEndpointRequest -from .types.registration_service import CreateNamespaceRequest -from .types.registration_service import CreateServiceRequest -from .types.registration_service import DeleteEndpointRequest -from .types.registration_service import DeleteNamespaceRequest -from .types.registration_service import DeleteServiceRequest -from .types.registration_service import GetEndpointRequest -from .types.registration_service import GetNamespaceRequest -from .types.registration_service import GetServiceRequest -from .types.registration_service import ListEndpointsRequest -from .types.registration_service import ListEndpointsResponse -from .types.registration_service import ListNamespacesRequest -from .types.registration_service import ListNamespacesResponse -from .types.registration_service import ListServicesRequest -from .types.registration_service import ListServicesResponse -from .types.registration_service import UpdateEndpointRequest -from .types.registration_service import UpdateNamespaceRequest -from .types.registration_service import UpdateServiceRequest -from .types.service import Service - -__all__ = ( - 'LookupServiceAsyncClient', - 'RegistrationServiceAsyncClient', -'CreateEndpointRequest', -'CreateNamespaceRequest', -'CreateServiceRequest', -'DeleteEndpointRequest', -'DeleteNamespaceRequest', -'DeleteServiceRequest', -'Endpoint', -'GetEndpointRequest', -'GetNamespaceRequest', -'GetServiceRequest', -'ListEndpointsRequest', -'ListEndpointsResponse', -'ListNamespacesRequest', -'ListNamespacesResponse', -'ListServicesRequest', -'ListServicesResponse', -'LookupServiceClient', -'Namespace', -'RegistrationServiceClient', -'ResolveServiceRequest', -'ResolveServiceResponse', -'Service', -'UpdateEndpointRequest', -'UpdateNamespaceRequest', -'UpdateServiceRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/gapic_metadata.json deleted file mode 100644 index 55647f3f..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/gapic_metadata.json +++ /dev/null @@ -1,227 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.servicedirectory_v1", - "protoPackage": "google.cloud.servicedirectory.v1", - "schema": "1.0", - "services": { - "LookupService": { - "clients": { - "grpc": { - "libraryClient": "LookupServiceClient", - "rpcs": { - "ResolveService": { - "methods": [ - "resolve_service" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LookupServiceAsyncClient", - "rpcs": { - "ResolveService": { - "methods": [ - "resolve_service" - ] - } - } - } - } - }, - "RegistrationService": { - "clients": { - "grpc": { - "libraryClient": "RegistrationServiceClient", - "rpcs": { - "CreateEndpoint": { - "methods": [ - "create_endpoint" - ] - }, - "CreateNamespace": { - "methods": [ - "create_namespace" - ] - }, - "CreateService": { - "methods": [ - "create_service" - ] - }, - "DeleteEndpoint": { - "methods": [ - "delete_endpoint" - ] - }, - "DeleteNamespace": { - "methods": [ - "delete_namespace" - ] - }, - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GetEndpoint": { - "methods": [ - "get_endpoint" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNamespace": { - "methods": [ - "get_namespace" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "ListEndpoints": { - "methods": [ - "list_endpoints" - ] - }, - "ListNamespaces": { - "methods": [ - "list_namespaces" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateEndpoint": { - "methods": [ - "update_endpoint" - ] - }, - "UpdateNamespace": { - "methods": [ - "update_namespace" - ] - }, - "UpdateService": { - "methods": [ - "update_service" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RegistrationServiceAsyncClient", - "rpcs": { - "CreateEndpoint": { - "methods": [ - "create_endpoint" - ] - }, - "CreateNamespace": { - "methods": [ - "create_namespace" - ] - }, - "CreateService": { - "methods": [ - "create_service" - ] - }, - "DeleteEndpoint": { - "methods": [ - "delete_endpoint" - ] - }, - "DeleteNamespace": { - "methods": [ - "delete_namespace" - ] - }, - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GetEndpoint": { - "methods": [ - "get_endpoint" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNamespace": { - "methods": [ - "get_namespace" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "ListEndpoints": { - "methods": [ - "list_endpoints" - ] - }, - "ListNamespaces": { - "methods": [ - "list_namespaces" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateEndpoint": { - "methods": [ - "update_endpoint" - ] - }, - "UpdateNamespace": { - "methods": [ - "update_namespace" - ] - }, - "UpdateService": { - "methods": [ - "update_service" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/py.typed b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/py.typed deleted file mode 100644 index 6790e24b..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-servicedirectory package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/__init__.py +++ /dev/null @@ -1,15 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py deleted file mode 100644 index 926753ac..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 LookupServiceClient -from .async_client import LookupServiceAsyncClient - -__all__ = ( - 'LookupServiceClient', - 'LookupServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py deleted file mode 100644 index ec02058f..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py +++ /dev/null @@ -1,226 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicedirectory_v1.types import lookup_service -from google.cloud.servicedirectory_v1.types import service -from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport -from .client import LookupServiceClient - - -class LookupServiceAsyncClient: - """Service Directory API for looking up service data at runtime.""" - - _client: LookupServiceClient - - DEFAULT_ENDPOINT = LookupServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LookupServiceClient.DEFAULT_MTLS_ENDPOINT - - endpoint_path = staticmethod(LookupServiceClient.endpoint_path) - parse_endpoint_path = staticmethod(LookupServiceClient.parse_endpoint_path) - service_path = staticmethod(LookupServiceClient.service_path) - parse_service_path = staticmethod(LookupServiceClient.parse_service_path) - common_billing_account_path = staticmethod(LookupServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LookupServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(LookupServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(LookupServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(LookupServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(LookupServiceClient.parse_common_organization_path) - common_project_path = staticmethod(LookupServiceClient.common_project_path) - parse_common_project_path = staticmethod(LookupServiceClient.parse_common_project_path) - common_location_path = staticmethod(LookupServiceClient.common_location_path) - parse_common_location_path = staticmethod(LookupServiceClient.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: - LookupServiceAsyncClient: The constructed client. - """ - return LookupServiceClient.from_service_account_info.__func__(LookupServiceAsyncClient, 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: - LookupServiceAsyncClient: The constructed client. - """ - return LookupServiceClient.from_service_account_file.__func__(LookupServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> LookupServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LookupServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(LookupServiceClient).get_transport_class, type(LookupServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, LookupServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the lookup 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 (Union[str, ~.LookupServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = LookupServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def resolve_service(self, - request: lookup_service.ResolveServiceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> lookup_service.ResolveServiceResponse: - r"""Returns a [service][google.cloud.servicedirectory.v1.Service] - and its associated endpoints. Resolving a service is not - considered an active developer method. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.ResolveServiceRequest`): - The request object. The request message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. - Looks up a service by its name, returns the service and - its endpoints. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.servicedirectory_v1.types.ResolveServiceResponse: - The response message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. - - """ - # Create or coerce a protobuf request object. - request = lookup_service.ResolveServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.resolve_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-servicedirectory", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "LookupServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/client.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/client.py deleted file mode 100644 index ecef1ebe..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/client.py +++ /dev/null @@ -1,433 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -from google.cloud.servicedirectory_v1.types import lookup_service -from google.cloud.servicedirectory_v1.types import service -from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import LookupServiceGrpcTransport -from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport - - -class LookupServiceClientMeta(type): - """Metaclass for the LookupService 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[LookupServiceTransport]] - _transport_registry["grpc"] = LookupServiceGrpcTransport - _transport_registry["grpc_asyncio"] = LookupServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[LookupServiceTransport]: - """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 LookupServiceClient(metaclass=LookupServiceClientMeta): - """Service Directory API for looking up service data at runtime.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "servicedirectory.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LookupServiceClient: 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: - LookupServiceClient: 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) -> LookupServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LookupServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def endpoint_path(project: str,location: str,namespace: str,service: str,endpoint: str,) -> str: - """Returns a fully-qualified endpoint string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) - - @staticmethod - def parse_endpoint_path(path: str) -> Dict[str,str]: - """Parses a endpoint path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_path(project: str,location: str,namespace: str,service: str,) -> str: - """Returns a fully-qualified service string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - - @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: - """Parses a service path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, LookupServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the lookup 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 (Union[str, LookupServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, LookupServiceTransport): - # transport is a LookupServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def resolve_service(self, - request: Union[lookup_service.ResolveServiceRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> lookup_service.ResolveServiceResponse: - r"""Returns a [service][google.cloud.servicedirectory.v1.Service] - and its associated endpoints. Resolving a service is not - considered an active developer method. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.ResolveServiceRequest, dict]): - The request object. The request message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. - Looks up a service by its name, returns the service and - its endpoints. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.servicedirectory_v1.types.ResolveServiceResponse: - The response message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a lookup_service.ResolveServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, lookup_service.ResolveServiceRequest): - request = lookup_service.ResolveServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.resolve_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-servicedirectory", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "LookupServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py deleted file mode 100644 index 437f5631..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 LookupServiceTransport -from .grpc import LookupServiceGrpcTransport -from .grpc_asyncio import LookupServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LookupServiceTransport]] -_transport_registry['grpc'] = LookupServiceGrpcTransport -_transport_registry['grpc_asyncio'] = LookupServiceGrpcAsyncIOTransport - -__all__ = ( - 'LookupServiceTransport', - 'LookupServiceGrpcTransport', - 'LookupServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py deleted file mode 100644 index 68b2b195..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py +++ /dev/null @@ -1,177 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicedirectory_v1.types import lookup_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-servicedirectory', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class LookupServiceTransport(abc.ABC): - """Abstract transport class for LookupService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'servicedirectory.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.resolve_service: gapic_v1.method.wrap_method( - self.resolve_service, - 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 resolve_service(self) -> Callable[ - [lookup_service.ResolveServiceRequest], - Union[ - lookup_service.ResolveServiceResponse, - Awaitable[lookup_service.ResolveServiceResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'LookupServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py deleted file mode 100644 index 283755da..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py +++ /dev/null @@ -1,256 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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.servicedirectory_v1.types import lookup_service -from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO - - -class LookupServiceGrpcTransport(LookupServiceTransport): - """gRPC backend transport for LookupService. - - Service Directory API for looking up service data at runtime. - - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 resolve_service(self) -> Callable[ - [lookup_service.ResolveServiceRequest], - lookup_service.ResolveServiceResponse]: - r"""Return a callable for the resolve service method over gRPC. - - Returns a [service][google.cloud.servicedirectory.v1.Service] - and its associated endpoints. Resolving a service is not - considered an active developer method. - - Returns: - Callable[[~.ResolveServiceRequest], - ~.ResolveServiceResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'resolve_service' not in self._stubs: - self._stubs['resolve_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.LookupService/ResolveService', - request_serializer=lookup_service.ResolveServiceRequest.serialize, - response_deserializer=lookup_service.ResolveServiceResponse.deserialize, - ) - return self._stubs['resolve_service'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'LookupServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py deleted file mode 100644 index d20b82e4..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,261 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.servicedirectory_v1.types import lookup_service -from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import LookupServiceGrpcTransport - - -class LookupServiceGrpcAsyncIOTransport(LookupServiceTransport): - """gRPC AsyncIO backend transport for LookupService. - - Service Directory API for looking up service data at runtime. - - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def resolve_service(self) -> Callable[ - [lookup_service.ResolveServiceRequest], - Awaitable[lookup_service.ResolveServiceResponse]]: - r"""Return a callable for the resolve service method over gRPC. - - Returns a [service][google.cloud.servicedirectory.v1.Service] - and its associated endpoints. Resolving a service is not - considered an active developer method. - - Returns: - Callable[[~.ResolveServiceRequest], - Awaitable[~.ResolveServiceResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'resolve_service' not in self._stubs: - self._stubs['resolve_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.LookupService/ResolveService', - request_serializer=lookup_service.ResolveServiceRequest.serialize, - response_deserializer=lookup_service.ResolveServiceResponse.deserialize, - ) - return self._stubs['resolve_service'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'LookupServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/__init__.py deleted file mode 100644 index 5097508c..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 RegistrationServiceClient -from .async_client import RegistrationServiceAsyncClient - -__all__ = ( - 'RegistrationServiceClient', - 'RegistrationServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/async_client.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/async_client.py deleted file mode 100644 index b2aa3e9e..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/async_client.py +++ /dev/null @@ -1,1736 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicedirectory_v1.services.registration_service import pagers -from google.cloud.servicedirectory_v1.types import endpoint -from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1.types import namespace -from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1.types import registration_service -from google.cloud.servicedirectory_v1.types import service -from google.cloud.servicedirectory_v1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport -from .client import RegistrationServiceClient - - -class RegistrationServiceAsyncClient: - """Service Directory API for registering services. It defines the - following resource model: - - - The API has a collection of - [Namespace][google.cloud.servicedirectory.v1.Namespace] - resources, named ``projects/*/locations/*/namespaces/*``. - - - Each Namespace has a collection of - [Service][google.cloud.servicedirectory.v1.Service] resources, - named ``projects/*/locations/*/namespaces/*/services/*``. - - - Each Service has a collection of - [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, - named - ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. - """ - - _client: RegistrationServiceClient - - DEFAULT_ENDPOINT = RegistrationServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RegistrationServiceClient.DEFAULT_MTLS_ENDPOINT - - endpoint_path = staticmethod(RegistrationServiceClient.endpoint_path) - parse_endpoint_path = staticmethod(RegistrationServiceClient.parse_endpoint_path) - namespace_path = staticmethod(RegistrationServiceClient.namespace_path) - parse_namespace_path = staticmethod(RegistrationServiceClient.parse_namespace_path) - service_path = staticmethod(RegistrationServiceClient.service_path) - parse_service_path = staticmethod(RegistrationServiceClient.parse_service_path) - common_billing_account_path = staticmethod(RegistrationServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RegistrationServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RegistrationServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(RegistrationServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(RegistrationServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(RegistrationServiceClient.parse_common_organization_path) - common_project_path = staticmethod(RegistrationServiceClient.common_project_path) - parse_common_project_path = staticmethod(RegistrationServiceClient.parse_common_project_path) - common_location_path = staticmethod(RegistrationServiceClient.common_location_path) - parse_common_location_path = staticmethod(RegistrationServiceClient.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: - RegistrationServiceAsyncClient: The constructed client. - """ - return RegistrationServiceClient.from_service_account_info.__func__(RegistrationServiceAsyncClient, 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: - RegistrationServiceAsyncClient: The constructed client. - """ - return RegistrationServiceClient.from_service_account_file.__func__(RegistrationServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> RegistrationServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RegistrationServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RegistrationServiceClient).get_transport_class, type(RegistrationServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, RegistrationServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the registration 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 (Union[str, ~.RegistrationServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RegistrationServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_namespace(self, - request: registration_service.CreateNamespaceRequest = None, - *, - parent: str = None, - namespace: gcs_namespace.Namespace = None, - namespace_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_namespace.Namespace: - r"""Creates a namespace, and returns the new Namespace. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.CreateNamespaceRequest`): - The request object. The request message for - [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1.RegistrationService.CreateNamespace]. - parent (:class:`str`): - Required. The resource name of the - project and location the namespace will - be created in. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - namespace (:class:`google.cloud.servicedirectory_v1.types.Namespace`): - Required. A namespace with initial - fields set. - - This corresponds to the ``namespace`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - namespace_id (:class:`str`): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``namespace_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, namespace, namespace_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.CreateNamespaceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if namespace is not None: - request.namespace = namespace - if namespace_id is not None: - request.namespace_id = namespace_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_namespace, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_namespaces(self, - request: registration_service.ListNamespacesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNamespacesAsyncPager: - r"""Lists all namespaces. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.ListNamespacesRequest`): - The request object. The request message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. - parent (:class:`str`): - Required. The resource name of the - project and location whose namespaces - we'd like to list. - - 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.servicedirectory_v1.services.registration_service.pagers.ListNamespacesAsyncPager: - The response message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.ListNamespacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_namespaces, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListNamespacesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_namespace(self, - request: registration_service.GetNamespaceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> namespace.Namespace: - r"""Gets a namespace. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.GetNamespaceRequest`): - The request object. The request message for - [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1.RegistrationService.GetNamespace]. - name (:class:`str`): - Required. The name of the namespace - to retrieve. - - 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.servicedirectory_v1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.GetNamespaceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_namespace, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_namespace(self, - request: registration_service.UpdateNamespaceRequest = None, - *, - namespace: gcs_namespace.Namespace = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_namespace.Namespace: - r"""Updates a namespace. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.UpdateNamespaceRequest`): - The request object. The request message for - [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1.RegistrationService.UpdateNamespace]. - namespace (:class:`google.cloud.servicedirectory_v1.types.Namespace`): - Required. The updated namespace. - This corresponds to the ``namespace`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([namespace, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.UpdateNamespaceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if namespace is not None: - request.namespace = namespace - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_namespace, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("namespace.name", request.namespace.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_namespace(self, - request: registration_service.DeleteNamespaceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a namespace. This also deletes all services - and endpoints in the namespace. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.DeleteNamespaceRequest`): - The request object. The request message for - [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1.RegistrationService.DeleteNamespace]. - name (:class:`str`): - Required. The name of the namespace - to delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.DeleteNamespaceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_namespace, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def create_service(self, - request: registration_service.CreateServiceRequest = None, - *, - parent: str = None, - service: gcs_service.Service = None, - service_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_service.Service: - r"""Creates a service, and returns the new Service. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.CreateServiceRequest`): - The request object. The request message for - [RegistrationService.CreateService][google.cloud.servicedirectory.v1.RegistrationService.CreateService]. - parent (:class:`str`): - Required. The resource name of the - namespace this service will belong to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service (:class:`google.cloud.servicedirectory_v1.types.Service`): - Required. A service with initial - fields set. - - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_id (:class:`str`): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``service_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, service, service_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.CreateServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if service is not None: - request.service = service - if service_id is not None: - request.service_id = service_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_services(self, - request: registration_service.ListServicesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServicesAsyncPager: - r"""Lists all services belonging to a namespace. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.ListServicesRequest`): - The request object. The request message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. - parent (:class:`str`): - Required. The resource name of the - namespace whose services we'd like to - list. - - 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.servicedirectory_v1.services.registration_service.pagers.ListServicesAsyncPager: - The response message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.ListServicesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_services, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServicesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_service(self, - request: registration_service.GetServiceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.Service: - r"""Gets a service. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.GetServiceRequest`): - The request object. The request message for - [RegistrationService.GetService][google.cloud.servicedirectory.v1.RegistrationService.GetService]. - This should not be used for looking up a service. - Insead, use the `resolve` method as it will contain all - endpoints and associated metadata. - name (:class:`str`): - Required. The name of the service to - get. - - 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.servicedirectory_v1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.GetServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_service(self, - request: registration_service.UpdateServiceRequest = None, - *, - service: gcs_service.Service = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_service.Service: - r"""Updates a service. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.UpdateServiceRequest`): - The request object. The request message for - [RegistrationService.UpdateService][google.cloud.servicedirectory.v1.RegistrationService.UpdateService]. - service (:class:`google.cloud.servicedirectory_v1.types.Service`): - Required. The updated service. - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.UpdateServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service is not None: - request.service = service - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service.name", request.service.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_service(self, - request: registration_service.DeleteServiceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a service. This also deletes all endpoints - associated with the service. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.DeleteServiceRequest`): - The request object. The request message for - [RegistrationService.DeleteService][google.cloud.servicedirectory.v1.RegistrationService.DeleteService]. - name (:class:`str`): - Required. The name of the service to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.DeleteServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def create_endpoint(self, - request: registration_service.CreateEndpointRequest = None, - *, - parent: str = None, - endpoint: gcs_endpoint.Endpoint = None, - endpoint_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_endpoint.Endpoint: - r"""Creates a endpoint, and returns the new Endpoint. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.CreateEndpointRequest`): - The request object. The request message for - [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.CreateEndpoint]. - parent (:class:`str`): - Required. The resource name of the - service that this endpoint provides. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint (:class:`google.cloud.servicedirectory_v1.types.Endpoint`): - Required. A endpoint with initial - fields set. - - This corresponds to the ``endpoint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint_id (:class:`str`): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``endpoint_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, endpoint, endpoint_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.CreateEndpointRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if endpoint is not None: - request.endpoint = endpoint - if endpoint_id is not None: - request.endpoint_id = endpoint_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_endpoint, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_endpoints(self, - request: registration_service.ListEndpointsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEndpointsAsyncPager: - r"""Lists all endpoints. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.ListEndpointsRequest`): - The request object. The request message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. - parent (:class:`str`): - Required. The resource name of the - service whose endpoints we'd like to - list. - - 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.servicedirectory_v1.services.registration_service.pagers.ListEndpointsAsyncPager: - The response message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.ListEndpointsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_endpoints, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListEndpointsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_endpoint(self, - request: registration_service.GetEndpointRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> endpoint.Endpoint: - r"""Gets a endpoint. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.GetEndpointRequest`): - The request object. The request message for - [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1.RegistrationService.GetEndpoint]. - This should not be used to lookup endpoints at runtime. - Instead, use the `resolve` method. - name (:class:`str`): - Required. The name of the endpoint to - get. - - 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.servicedirectory_v1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.GetEndpointRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_endpoint, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_endpoint(self, - request: registration_service.UpdateEndpointRequest = None, - *, - endpoint: gcs_endpoint.Endpoint = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_endpoint.Endpoint: - r"""Updates a endpoint. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.UpdateEndpointRequest`): - The request object. The request message for - [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.UpdateEndpoint]. - endpoint (:class:`google.cloud.servicedirectory_v1.types.Endpoint`): - Required. The updated endpoint. - This corresponds to the ``endpoint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([endpoint, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.UpdateEndpointRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if endpoint is not None: - request.endpoint = endpoint - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_endpoint, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("endpoint.name", request.endpoint.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_endpoint(self, - request: registration_service.DeleteEndpointRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a endpoint. - - Args: - request (:class:`google.cloud.servicedirectory_v1.types.DeleteEndpointRequest`): - The request object. The request message for - [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1.RegistrationService.DeleteEndpoint]. - name (:class:`str`): - Required. The name of the endpoint to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.DeleteEndpointRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_endpoint, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_iam_policy(self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM Policy for a resource (namespace or - service only). - - Args: - request (:class:`google.iam.v1.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: - google.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy(self, - request: iam_policy_pb2.SetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM Policy for a resource (namespace or - service only). - - Args: - request (:class:`google.iam.v1.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: - google.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def test_iam_permissions(self, - request: iam_policy_pb2.TestIamPermissionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests IAM permissions for a resource (namespace or - service only). - - Args: - request (:class:`google.iam.v1.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: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-servicedirectory", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "RegistrationServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/client.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/client.py deleted file mode 100644 index a64d2f62..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/client.py +++ /dev/null @@ -1,1948 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -from google.cloud.servicedirectory_v1.services.registration_service import pagers -from google.cloud.servicedirectory_v1.types import endpoint -from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1.types import namespace -from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1.types import registration_service -from google.cloud.servicedirectory_v1.types import service -from google.cloud.servicedirectory_v1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RegistrationServiceGrpcTransport -from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport - - -class RegistrationServiceClientMeta(type): - """Metaclass for the RegistrationService 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[RegistrationServiceTransport]] - _transport_registry["grpc"] = RegistrationServiceGrpcTransport - _transport_registry["grpc_asyncio"] = RegistrationServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[RegistrationServiceTransport]: - """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 RegistrationServiceClient(metaclass=RegistrationServiceClientMeta): - """Service Directory API for registering services. It defines the - following resource model: - - - The API has a collection of - [Namespace][google.cloud.servicedirectory.v1.Namespace] - resources, named ``projects/*/locations/*/namespaces/*``. - - - Each Namespace has a collection of - [Service][google.cloud.servicedirectory.v1.Service] resources, - named ``projects/*/locations/*/namespaces/*/services/*``. - - - Each Service has a collection of - [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, - named - ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "servicedirectory.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegistrationServiceClient: 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: - RegistrationServiceClient: 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) -> RegistrationServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RegistrationServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def endpoint_path(project: str,location: str,namespace: str,service: str,endpoint: str,) -> str: - """Returns a fully-qualified endpoint string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) - - @staticmethod - def parse_endpoint_path(path: str) -> Dict[str,str]: - """Parses a endpoint path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def namespace_path(project: str,location: str,namespace: str,) -> str: - """Returns a fully-qualified namespace string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}".format(project=project, location=location, namespace=namespace, ) - - @staticmethod - def parse_namespace_path(path: str) -> Dict[str,str]: - """Parses a namespace path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_path(project: str,location: str,namespace: str,service: str,) -> str: - """Returns a fully-qualified service string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - - @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: - """Parses a service path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RegistrationServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the registration 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 (Union[str, RegistrationServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RegistrationServiceTransport): - # transport is a RegistrationServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_namespace(self, - request: Union[registration_service.CreateNamespaceRequest, dict] = None, - *, - parent: str = None, - namespace: gcs_namespace.Namespace = None, - namespace_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_namespace.Namespace: - r"""Creates a namespace, and returns the new Namespace. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.CreateNamespaceRequest, dict]): - The request object. The request message for - [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1.RegistrationService.CreateNamespace]. - parent (str): - Required. The resource name of the - project and location the namespace will - be created in. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - namespace (google.cloud.servicedirectory_v1.types.Namespace): - Required. A namespace with initial - fields set. - - This corresponds to the ``namespace`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - namespace_id (str): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``namespace_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, namespace, namespace_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.CreateNamespaceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.CreateNamespaceRequest): - request = registration_service.CreateNamespaceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if namespace is not None: - request.namespace = namespace - if namespace_id is not None: - request.namespace_id = namespace_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_namespace] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_namespaces(self, - request: Union[registration_service.ListNamespacesRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNamespacesPager: - r"""Lists all namespaces. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.ListNamespacesRequest, dict]): - The request object. The request message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. - parent (str): - Required. The resource name of the - project and location whose namespaces - we'd like to list. - - 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.servicedirectory_v1.services.registration_service.pagers.ListNamespacesPager: - The response message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.ListNamespacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.ListNamespacesRequest): - request = registration_service.ListNamespacesRequest(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_namespaces] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListNamespacesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_namespace(self, - request: Union[registration_service.GetNamespaceRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> namespace.Namespace: - r"""Gets a namespace. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.GetNamespaceRequest, dict]): - The request object. The request message for - [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1.RegistrationService.GetNamespace]. - name (str): - Required. The name of the namespace - to retrieve. - - 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.servicedirectory_v1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.GetNamespaceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.GetNamespaceRequest): - request = registration_service.GetNamespaceRequest(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_namespace] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_namespace(self, - request: Union[registration_service.UpdateNamespaceRequest, dict] = None, - *, - namespace: gcs_namespace.Namespace = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_namespace.Namespace: - r"""Updates a namespace. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.UpdateNamespaceRequest, dict]): - The request object. The request message for - [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1.RegistrationService.UpdateNamespace]. - namespace (google.cloud.servicedirectory_v1.types.Namespace): - Required. The updated namespace. - This corresponds to the ``namespace`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([namespace, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.UpdateNamespaceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.UpdateNamespaceRequest): - request = registration_service.UpdateNamespaceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if namespace is not None: - request.namespace = namespace - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_namespace] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("namespace.name", request.namespace.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_namespace(self, - request: Union[registration_service.DeleteNamespaceRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a namespace. This also deletes all services - and endpoints in the namespace. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.DeleteNamespaceRequest, dict]): - The request object. The request message for - [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1.RegistrationService.DeleteNamespace]. - name (str): - Required. The name of the namespace - to delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.DeleteNamespaceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.DeleteNamespaceRequest): - request = registration_service.DeleteNamespaceRequest(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_namespace] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def create_service(self, - request: Union[registration_service.CreateServiceRequest, dict] = None, - *, - parent: str = None, - service: gcs_service.Service = None, - service_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_service.Service: - r"""Creates a service, and returns the new Service. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.CreateServiceRequest, dict]): - The request object. The request message for - [RegistrationService.CreateService][google.cloud.servicedirectory.v1.RegistrationService.CreateService]. - parent (str): - Required. The resource name of the - namespace this service will belong to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service (google.cloud.servicedirectory_v1.types.Service): - Required. A service with initial - fields set. - - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_id (str): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``service_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, service, service_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.CreateServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.CreateServiceRequest): - request = registration_service.CreateServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if service is not None: - request.service = service - if service_id is not None: - request.service_id = service_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_services(self, - request: Union[registration_service.ListServicesRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServicesPager: - r"""Lists all services belonging to a namespace. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.ListServicesRequest, dict]): - The request object. The request message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. - parent (str): - Required. The resource name of the - namespace whose services we'd like to - list. - - 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.servicedirectory_v1.services.registration_service.pagers.ListServicesPager: - The response message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.ListServicesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.ListServicesRequest): - request = registration_service.ListServicesRequest(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_services] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServicesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_service(self, - request: Union[registration_service.GetServiceRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.Service: - r"""Gets a service. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.GetServiceRequest, dict]): - The request object. The request message for - [RegistrationService.GetService][google.cloud.servicedirectory.v1.RegistrationService.GetService]. - This should not be used for looking up a service. - Insead, use the `resolve` method as it will contain all - endpoints and associated metadata. - name (str): - Required. The name of the service to - get. - - 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.servicedirectory_v1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.GetServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.GetServiceRequest): - request = registration_service.GetServiceRequest(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_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_service(self, - request: Union[registration_service.UpdateServiceRequest, dict] = None, - *, - service: gcs_service.Service = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_service.Service: - r"""Updates a service. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.UpdateServiceRequest, dict]): - The request object. The request message for - [RegistrationService.UpdateService][google.cloud.servicedirectory.v1.RegistrationService.UpdateService]. - service (google.cloud.servicedirectory_v1.types.Service): - Required. The updated service. - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.UpdateServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.UpdateServiceRequest): - request = registration_service.UpdateServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service is not None: - request.service = service - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service.name", request.service.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_service(self, - request: Union[registration_service.DeleteServiceRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a service. This also deletes all endpoints - associated with the service. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.DeleteServiceRequest, dict]): - The request object. The request message for - [RegistrationService.DeleteService][google.cloud.servicedirectory.v1.RegistrationService.DeleteService]. - name (str): - Required. The name of the service to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.DeleteServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.DeleteServiceRequest): - request = registration_service.DeleteServiceRequest(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_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def create_endpoint(self, - request: Union[registration_service.CreateEndpointRequest, dict] = None, - *, - parent: str = None, - endpoint: gcs_endpoint.Endpoint = None, - endpoint_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_endpoint.Endpoint: - r"""Creates a endpoint, and returns the new Endpoint. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.CreateEndpointRequest, dict]): - The request object. The request message for - [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.CreateEndpoint]. - parent (str): - Required. The resource name of the - service that this endpoint provides. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint (google.cloud.servicedirectory_v1.types.Endpoint): - Required. A endpoint with initial - fields set. - - This corresponds to the ``endpoint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint_id (str): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``endpoint_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, endpoint, endpoint_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.CreateEndpointRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.CreateEndpointRequest): - request = registration_service.CreateEndpointRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if endpoint is not None: - request.endpoint = endpoint - if endpoint_id is not None: - request.endpoint_id = endpoint_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_endpoint] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_endpoints(self, - request: Union[registration_service.ListEndpointsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEndpointsPager: - r"""Lists all endpoints. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.ListEndpointsRequest, dict]): - The request object. The request message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. - parent (str): - Required. The resource name of the - service whose endpoints we'd like to - list. - - 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.servicedirectory_v1.services.registration_service.pagers.ListEndpointsPager: - The response message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.ListEndpointsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.ListEndpointsRequest): - request = registration_service.ListEndpointsRequest(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_endpoints] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListEndpointsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_endpoint(self, - request: Union[registration_service.GetEndpointRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> endpoint.Endpoint: - r"""Gets a endpoint. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.GetEndpointRequest, dict]): - The request object. The request message for - [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1.RegistrationService.GetEndpoint]. - This should not be used to lookup endpoints at runtime. - Instead, use the `resolve` method. - name (str): - Required. The name of the endpoint to - get. - - 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.servicedirectory_v1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.GetEndpointRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.GetEndpointRequest): - request = registration_service.GetEndpointRequest(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_endpoint] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_endpoint(self, - request: Union[registration_service.UpdateEndpointRequest, dict] = None, - *, - endpoint: gcs_endpoint.Endpoint = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_endpoint.Endpoint: - r"""Updates a endpoint. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.UpdateEndpointRequest, dict]): - The request object. The request message for - [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.UpdateEndpoint]. - endpoint (google.cloud.servicedirectory_v1.types.Endpoint): - Required. The updated endpoint. - This corresponds to the ``endpoint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([endpoint, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.UpdateEndpointRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.UpdateEndpointRequest): - request = registration_service.UpdateEndpointRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if endpoint is not None: - request.endpoint = endpoint - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_endpoint] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("endpoint.name", request.endpoint.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_endpoint(self, - request: Union[registration_service.DeleteEndpointRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a endpoint. - - Args: - request (Union[google.cloud.servicedirectory_v1.types.DeleteEndpointRequest, dict]): - The request object. The request message for - [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1.RegistrationService.DeleteEndpoint]. - name (str): - Required. The name of the endpoint to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.DeleteEndpointRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.DeleteEndpointRequest): - request = registration_service.DeleteEndpointRequest(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_endpoint] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM Policy for a resource (namespace or - service only). - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - 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: - google.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy(self, - request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM Policy for a resource (namespace or - service only). - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - 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: - google.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def test_iam_permissions(self, - request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests IAM permissions for a resource (namespace or - service only). - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - 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: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-servicedirectory", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "RegistrationServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/pagers.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/pagers.py deleted file mode 100644 index 682e1d7c..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/pagers.py +++ /dev/null @@ -1,387 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.servicedirectory_v1.types import endpoint -from google.cloud.servicedirectory_v1.types import namespace -from google.cloud.servicedirectory_v1.types import registration_service -from google.cloud.servicedirectory_v1.types import service - - -class ListNamespacesPager: - """A pager for iterating through ``list_namespaces`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1.types.ListNamespacesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``namespaces`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNamespaces`` requests and continue to iterate - through the ``namespaces`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1.types.ListNamespacesResponse` - 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[..., registration_service.ListNamespacesResponse], - request: registration_service.ListNamespacesRequest, - response: registration_service.ListNamespacesResponse, - *, - 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.servicedirectory_v1.types.ListNamespacesRequest): - The initial request object. - response (google.cloud.servicedirectory_v1.types.ListNamespacesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListNamespacesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registration_service.ListNamespacesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[namespace.Namespace]: - for page in self.pages: - yield from page.namespaces - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNamespacesAsyncPager: - """A pager for iterating through ``list_namespaces`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1.types.ListNamespacesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``namespaces`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNamespaces`` requests and continue to iterate - through the ``namespaces`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1.types.ListNamespacesResponse` - 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[registration_service.ListNamespacesResponse]], - request: registration_service.ListNamespacesRequest, - response: registration_service.ListNamespacesResponse, - *, - 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.servicedirectory_v1.types.ListNamespacesRequest): - The initial request object. - response (google.cloud.servicedirectory_v1.types.ListNamespacesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListNamespacesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registration_service.ListNamespacesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[namespace.Namespace]: - async def async_generator(): - async for page in self.pages: - for response in page.namespaces: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServicesPager: - """A pager for iterating through ``list_services`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1.types.ListServicesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``services`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServices`` requests and continue to iterate - through the ``services`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1.types.ListServicesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., registration_service.ListServicesResponse], - request: registration_service.ListServicesRequest, - response: registration_service.ListServicesResponse, - *, - 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.servicedirectory_v1.types.ListServicesRequest): - The initial request object. - response (google.cloud.servicedirectory_v1.types.ListServicesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListServicesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registration_service.ListServicesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[service.Service]: - for page in self.pages: - yield from page.services - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServicesAsyncPager: - """A pager for iterating through ``list_services`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1.types.ListServicesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``services`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServices`` requests and continue to iterate - through the ``services`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1.types.ListServicesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[registration_service.ListServicesResponse]], - request: registration_service.ListServicesRequest, - response: registration_service.ListServicesResponse, - *, - 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.servicedirectory_v1.types.ListServicesRequest): - The initial request object. - response (google.cloud.servicedirectory_v1.types.ListServicesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListServicesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registration_service.ListServicesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[service.Service]: - async def async_generator(): - async for page in self.pages: - for response in page.services: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEndpointsPager: - """A pager for iterating through ``list_endpoints`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1.types.ListEndpointsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``endpoints`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEndpoints`` requests and continue to iterate - through the ``endpoints`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1.types.ListEndpointsResponse` - 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[..., registration_service.ListEndpointsResponse], - request: registration_service.ListEndpointsRequest, - response: registration_service.ListEndpointsResponse, - *, - 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.servicedirectory_v1.types.ListEndpointsRequest): - The initial request object. - response (google.cloud.servicedirectory_v1.types.ListEndpointsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListEndpointsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registration_service.ListEndpointsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[endpoint.Endpoint]: - for page in self.pages: - yield from page.endpoints - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEndpointsAsyncPager: - """A pager for iterating through ``list_endpoints`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1.types.ListEndpointsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``endpoints`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEndpoints`` requests and continue to iterate - through the ``endpoints`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1.types.ListEndpointsResponse` - 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[registration_service.ListEndpointsResponse]], - request: registration_service.ListEndpointsRequest, - response: registration_service.ListEndpointsResponse, - *, - 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.servicedirectory_v1.types.ListEndpointsRequest): - The initial request object. - response (google.cloud.servicedirectory_v1.types.ListEndpointsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListEndpointsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registration_service.ListEndpointsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[endpoint.Endpoint]: - async def async_generator(): - async for page in self.pages: - for response in page.endpoints: - 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/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py deleted file mode 100644 index a584bf16..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 RegistrationServiceTransport -from .grpc import RegistrationServiceGrpcTransport -from .grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RegistrationServiceTransport]] -_transport_registry['grpc'] = RegistrationServiceGrpcTransport -_transport_registry['grpc_asyncio'] = RegistrationServiceGrpcAsyncIOTransport - -__all__ = ( - 'RegistrationServiceTransport', - 'RegistrationServiceGrpcTransport', - 'RegistrationServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py deleted file mode 100644 index 0a8e3d13..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py +++ /dev/null @@ -1,424 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicedirectory_v1.types import endpoint -from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1.types import namespace -from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1.types import registration_service -from google.cloud.servicedirectory_v1.types import service -from google.cloud.servicedirectory_v1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-servicedirectory', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class RegistrationServiceTransport(abc.ABC): - """Abstract transport class for RegistrationService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'servicedirectory.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_namespace: gapic_v1.method.wrap_method( - self.create_namespace, - default_timeout=None, - client_info=client_info, - ), - self.list_namespaces: gapic_v1.method.wrap_method( - self.list_namespaces, - default_timeout=None, - client_info=client_info, - ), - self.get_namespace: gapic_v1.method.wrap_method( - self.get_namespace, - default_timeout=None, - client_info=client_info, - ), - self.update_namespace: gapic_v1.method.wrap_method( - self.update_namespace, - default_timeout=None, - client_info=client_info, - ), - self.delete_namespace: gapic_v1.method.wrap_method( - self.delete_namespace, - default_timeout=None, - client_info=client_info, - ), - self.create_service: gapic_v1.method.wrap_method( - self.create_service, - default_timeout=None, - client_info=client_info, - ), - self.list_services: gapic_v1.method.wrap_method( - self.list_services, - default_timeout=None, - client_info=client_info, - ), - self.get_service: gapic_v1.method.wrap_method( - self.get_service, - default_timeout=None, - client_info=client_info, - ), - self.update_service: gapic_v1.method.wrap_method( - self.update_service, - default_timeout=None, - client_info=client_info, - ), - self.delete_service: gapic_v1.method.wrap_method( - self.delete_service, - default_timeout=None, - client_info=client_info, - ), - self.create_endpoint: gapic_v1.method.wrap_method( - self.create_endpoint, - default_timeout=None, - client_info=client_info, - ), - self.list_endpoints: gapic_v1.method.wrap_method( - self.list_endpoints, - default_timeout=None, - client_info=client_info, - ), - self.get_endpoint: gapic_v1.method.wrap_method( - self.get_endpoint, - default_timeout=None, - client_info=client_info, - ), - self.update_endpoint: gapic_v1.method.wrap_method( - self.update_endpoint, - default_timeout=None, - client_info=client_info, - ), - self.delete_endpoint: gapic_v1.method.wrap_method( - self.delete_endpoint, - 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, - ), - } - - 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 create_namespace(self) -> Callable[ - [registration_service.CreateNamespaceRequest], - Union[ - gcs_namespace.Namespace, - Awaitable[gcs_namespace.Namespace] - ]]: - raise NotImplementedError() - - @property - def list_namespaces(self) -> Callable[ - [registration_service.ListNamespacesRequest], - Union[ - registration_service.ListNamespacesResponse, - Awaitable[registration_service.ListNamespacesResponse] - ]]: - raise NotImplementedError() - - @property - def get_namespace(self) -> Callable[ - [registration_service.GetNamespaceRequest], - Union[ - namespace.Namespace, - Awaitable[namespace.Namespace] - ]]: - raise NotImplementedError() - - @property - def update_namespace(self) -> Callable[ - [registration_service.UpdateNamespaceRequest], - Union[ - gcs_namespace.Namespace, - Awaitable[gcs_namespace.Namespace] - ]]: - raise NotImplementedError() - - @property - def delete_namespace(self) -> Callable[ - [registration_service.DeleteNamespaceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_service(self) -> Callable[ - [registration_service.CreateServiceRequest], - Union[ - gcs_service.Service, - Awaitable[gcs_service.Service] - ]]: - raise NotImplementedError() - - @property - def list_services(self) -> Callable[ - [registration_service.ListServicesRequest], - Union[ - registration_service.ListServicesResponse, - Awaitable[registration_service.ListServicesResponse] - ]]: - raise NotImplementedError() - - @property - def get_service(self) -> Callable[ - [registration_service.GetServiceRequest], - Union[ - service.Service, - Awaitable[service.Service] - ]]: - raise NotImplementedError() - - @property - def update_service(self) -> Callable[ - [registration_service.UpdateServiceRequest], - Union[ - gcs_service.Service, - Awaitable[gcs_service.Service] - ]]: - raise NotImplementedError() - - @property - def delete_service(self) -> Callable[ - [registration_service.DeleteServiceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_endpoint(self) -> Callable[ - [registration_service.CreateEndpointRequest], - Union[ - gcs_endpoint.Endpoint, - Awaitable[gcs_endpoint.Endpoint] - ]]: - raise NotImplementedError() - - @property - def list_endpoints(self) -> Callable[ - [registration_service.ListEndpointsRequest], - Union[ - registration_service.ListEndpointsResponse, - Awaitable[registration_service.ListEndpointsResponse] - ]]: - raise NotImplementedError() - - @property - def get_endpoint(self) -> Callable[ - [registration_service.GetEndpointRequest], - Union[ - endpoint.Endpoint, - Awaitable[endpoint.Endpoint] - ]]: - raise NotImplementedError() - - @property - def update_endpoint(self) -> Callable[ - [registration_service.UpdateEndpointRequest], - Union[ - gcs_endpoint.Endpoint, - Awaitable[gcs_endpoint.Endpoint] - ]]: - raise NotImplementedError() - - @property - def delete_endpoint(self) -> Callable[ - [registration_service.DeleteEndpointRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - 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 set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - 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() - - -__all__ = ( - 'RegistrationServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py deleted file mode 100644 index a90023c2..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py +++ /dev/null @@ -1,724 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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.servicedirectory_v1.types import endpoint -from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1.types import namespace -from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1.types import registration_service -from google.cloud.servicedirectory_v1.types import service -from google.cloud.servicedirectory_v1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO - - -class RegistrationServiceGrpcTransport(RegistrationServiceTransport): - """gRPC backend transport for RegistrationService. - - Service Directory API for registering services. It defines the - following resource model: - - - The API has a collection of - [Namespace][google.cloud.servicedirectory.v1.Namespace] - resources, named ``projects/*/locations/*/namespaces/*``. - - - Each Namespace has a collection of - [Service][google.cloud.servicedirectory.v1.Service] resources, - named ``projects/*/locations/*/namespaces/*/services/*``. - - - Each Service has a collection of - [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, - named - ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. - - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_namespace(self) -> Callable[ - [registration_service.CreateNamespaceRequest], - gcs_namespace.Namespace]: - r"""Return a callable for the create namespace method over gRPC. - - Creates a namespace, and returns the new Namespace. - - Returns: - Callable[[~.CreateNamespaceRequest], - ~.Namespace]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['create_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/CreateNamespace', - request_serializer=registration_service.CreateNamespaceRequest.serialize, - response_deserializer=gcs_namespace.Namespace.deserialize, - ) - return self._stubs['create_namespace'] - - @property - def list_namespaces(self) -> Callable[ - [registration_service.ListNamespacesRequest], - registration_service.ListNamespacesResponse]: - r"""Return a callable for the list namespaces method over gRPC. - - Lists all namespaces. - - Returns: - Callable[[~.ListNamespacesRequest], - ~.ListNamespacesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespaces' not in self._stubs: - self._stubs['list_namespaces'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/ListNamespaces', - request_serializer=registration_service.ListNamespacesRequest.serialize, - response_deserializer=registration_service.ListNamespacesResponse.deserialize, - ) - return self._stubs['list_namespaces'] - - @property - def get_namespace(self) -> Callable[ - [registration_service.GetNamespaceRequest], - namespace.Namespace]: - r"""Return a callable for the get namespace method over gRPC. - - Gets a namespace. - - Returns: - Callable[[~.GetNamespaceRequest], - ~.Namespace]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['get_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/GetNamespace', - request_serializer=registration_service.GetNamespaceRequest.serialize, - response_deserializer=namespace.Namespace.deserialize, - ) - return self._stubs['get_namespace'] - - @property - def update_namespace(self) -> Callable[ - [registration_service.UpdateNamespaceRequest], - gcs_namespace.Namespace]: - r"""Return a callable for the update namespace method over gRPC. - - Updates a namespace. - - Returns: - Callable[[~.UpdateNamespaceRequest], - ~.Namespace]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['update_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/UpdateNamespace', - request_serializer=registration_service.UpdateNamespaceRequest.serialize, - response_deserializer=gcs_namespace.Namespace.deserialize, - ) - return self._stubs['update_namespace'] - - @property - def delete_namespace(self) -> Callable[ - [registration_service.DeleteNamespaceRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete namespace method over gRPC. - - Deletes a namespace. This also deletes all services - and endpoints in the namespace. - - Returns: - Callable[[~.DeleteNamespaceRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_namespace' not in self._stubs: - self._stubs['delete_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/DeleteNamespace', - request_serializer=registration_service.DeleteNamespaceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_namespace'] - - @property - def create_service(self) -> Callable[ - [registration_service.CreateServiceRequest], - gcs_service.Service]: - r"""Return a callable for the create service method over gRPC. - - Creates a service, and returns the new Service. - - Returns: - Callable[[~.CreateServiceRequest], - ~.Service]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_service' not in self._stubs: - self._stubs['create_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/CreateService', - request_serializer=registration_service.CreateServiceRequest.serialize, - response_deserializer=gcs_service.Service.deserialize, - ) - return self._stubs['create_service'] - - @property - def list_services(self) -> Callable[ - [registration_service.ListServicesRequest], - registration_service.ListServicesResponse]: - r"""Return a callable for the list services method over gRPC. - - Lists all services belonging to a namespace. - - Returns: - Callable[[~.ListServicesRequest], - ~.ListServicesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_services' not in self._stubs: - self._stubs['list_services'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/ListServices', - request_serializer=registration_service.ListServicesRequest.serialize, - response_deserializer=registration_service.ListServicesResponse.deserialize, - ) - return self._stubs['list_services'] - - @property - def get_service(self) -> Callable[ - [registration_service.GetServiceRequest], - service.Service]: - r"""Return a callable for the get service method over gRPC. - - Gets a service. - - Returns: - Callable[[~.GetServiceRequest], - ~.Service]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_service' not in self._stubs: - self._stubs['get_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/GetService', - request_serializer=registration_service.GetServiceRequest.serialize, - response_deserializer=service.Service.deserialize, - ) - return self._stubs['get_service'] - - @property - def update_service(self) -> Callable[ - [registration_service.UpdateServiceRequest], - gcs_service.Service]: - r"""Return a callable for the update service method over gRPC. - - Updates a service. - - Returns: - Callable[[~.UpdateServiceRequest], - ~.Service]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_service' not in self._stubs: - self._stubs['update_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/UpdateService', - request_serializer=registration_service.UpdateServiceRequest.serialize, - response_deserializer=gcs_service.Service.deserialize, - ) - return self._stubs['update_service'] - - @property - def delete_service(self) -> Callable[ - [registration_service.DeleteServiceRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete service method over gRPC. - - Deletes a service. This also deletes all endpoints - associated with the service. - - Returns: - Callable[[~.DeleteServiceRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_service' not in self._stubs: - self._stubs['delete_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/DeleteService', - request_serializer=registration_service.DeleteServiceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_service'] - - @property - def create_endpoint(self) -> Callable[ - [registration_service.CreateEndpointRequest], - gcs_endpoint.Endpoint]: - r"""Return a callable for the create endpoint method over gRPC. - - Creates a endpoint, and returns the new Endpoint. - - Returns: - Callable[[~.CreateEndpointRequest], - ~.Endpoint]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['create_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/CreateEndpoint', - request_serializer=registration_service.CreateEndpointRequest.serialize, - response_deserializer=gcs_endpoint.Endpoint.deserialize, - ) - return self._stubs['create_endpoint'] - - @property - def list_endpoints(self) -> Callable[ - [registration_service.ListEndpointsRequest], - registration_service.ListEndpointsResponse]: - r"""Return a callable for the list endpoints method over gRPC. - - Lists all endpoints. - - Returns: - Callable[[~.ListEndpointsRequest], - ~.ListEndpointsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoints' not in self._stubs: - self._stubs['list_endpoints'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/ListEndpoints', - request_serializer=registration_service.ListEndpointsRequest.serialize, - response_deserializer=registration_service.ListEndpointsResponse.deserialize, - ) - return self._stubs['list_endpoints'] - - @property - def get_endpoint(self) -> Callable[ - [registration_service.GetEndpointRequest], - endpoint.Endpoint]: - r"""Return a callable for the get endpoint method over gRPC. - - Gets a endpoint. - - Returns: - Callable[[~.GetEndpointRequest], - ~.Endpoint]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['get_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/GetEndpoint', - request_serializer=registration_service.GetEndpointRequest.serialize, - response_deserializer=endpoint.Endpoint.deserialize, - ) - return self._stubs['get_endpoint'] - - @property - def update_endpoint(self) -> Callable[ - [registration_service.UpdateEndpointRequest], - gcs_endpoint.Endpoint]: - r"""Return a callable for the update endpoint method over gRPC. - - Updates a endpoint. - - Returns: - Callable[[~.UpdateEndpointRequest], - ~.Endpoint]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['update_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/UpdateEndpoint', - request_serializer=registration_service.UpdateEndpointRequest.serialize, - response_deserializer=gcs_endpoint.Endpoint.deserialize, - ) - return self._stubs['update_endpoint'] - - @property - def delete_endpoint(self) -> Callable[ - [registration_service.DeleteEndpointRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete endpoint method over gRPC. - - Deletes a endpoint. - - Returns: - Callable[[~.DeleteEndpointRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_endpoint' not in self._stubs: - self._stubs['delete_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/DeleteEndpoint', - request_serializer=registration_service.DeleteEndpointRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_endpoint'] - - @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 Policy for a resource (namespace or - service only). - - 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.cloud.servicedirectory.v1.RegistrationService/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 Policy for a resource (namespace or - service only). - - 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.cloud.servicedirectory.v1.RegistrationService/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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 IAM permissions for a resource (namespace or - service only). - - 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.cloud.servicedirectory.v1.RegistrationService/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'RegistrationServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py deleted file mode 100644 index c0ebc5ac..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,729 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.servicedirectory_v1.types import endpoint -from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1.types import namespace -from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1.types import registration_service -from google.cloud.servicedirectory_v1.types import service -from google.cloud.servicedirectory_v1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import RegistrationServiceGrpcTransport - - -class RegistrationServiceGrpcAsyncIOTransport(RegistrationServiceTransport): - """gRPC AsyncIO backend transport for RegistrationService. - - Service Directory API for registering services. It defines the - following resource model: - - - The API has a collection of - [Namespace][google.cloud.servicedirectory.v1.Namespace] - resources, named ``projects/*/locations/*/namespaces/*``. - - - Each Namespace has a collection of - [Service][google.cloud.servicedirectory.v1.Service] resources, - named ``projects/*/locations/*/namespaces/*/services/*``. - - - Each Service has a collection of - [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, - named - ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. - - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_namespace(self) -> Callable[ - [registration_service.CreateNamespaceRequest], - Awaitable[gcs_namespace.Namespace]]: - r"""Return a callable for the create namespace method over gRPC. - - Creates a namespace, and returns the new Namespace. - - Returns: - Callable[[~.CreateNamespaceRequest], - Awaitable[~.Namespace]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['create_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/CreateNamespace', - request_serializer=registration_service.CreateNamespaceRequest.serialize, - response_deserializer=gcs_namespace.Namespace.deserialize, - ) - return self._stubs['create_namespace'] - - @property - def list_namespaces(self) -> Callable[ - [registration_service.ListNamespacesRequest], - Awaitable[registration_service.ListNamespacesResponse]]: - r"""Return a callable for the list namespaces method over gRPC. - - Lists all namespaces. - - Returns: - Callable[[~.ListNamespacesRequest], - Awaitable[~.ListNamespacesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespaces' not in self._stubs: - self._stubs['list_namespaces'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/ListNamespaces', - request_serializer=registration_service.ListNamespacesRequest.serialize, - response_deserializer=registration_service.ListNamespacesResponse.deserialize, - ) - return self._stubs['list_namespaces'] - - @property - def get_namespace(self) -> Callable[ - [registration_service.GetNamespaceRequest], - Awaitable[namespace.Namespace]]: - r"""Return a callable for the get namespace method over gRPC. - - Gets a namespace. - - Returns: - Callable[[~.GetNamespaceRequest], - Awaitable[~.Namespace]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['get_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/GetNamespace', - request_serializer=registration_service.GetNamespaceRequest.serialize, - response_deserializer=namespace.Namespace.deserialize, - ) - return self._stubs['get_namespace'] - - @property - def update_namespace(self) -> Callable[ - [registration_service.UpdateNamespaceRequest], - Awaitable[gcs_namespace.Namespace]]: - r"""Return a callable for the update namespace method over gRPC. - - Updates a namespace. - - Returns: - Callable[[~.UpdateNamespaceRequest], - Awaitable[~.Namespace]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['update_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/UpdateNamespace', - request_serializer=registration_service.UpdateNamespaceRequest.serialize, - response_deserializer=gcs_namespace.Namespace.deserialize, - ) - return self._stubs['update_namespace'] - - @property - def delete_namespace(self) -> Callable[ - [registration_service.DeleteNamespaceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete namespace method over gRPC. - - Deletes a namespace. This also deletes all services - and endpoints in the namespace. - - Returns: - Callable[[~.DeleteNamespaceRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_namespace' not in self._stubs: - self._stubs['delete_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/DeleteNamespace', - request_serializer=registration_service.DeleteNamespaceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_namespace'] - - @property - def create_service(self) -> Callable[ - [registration_service.CreateServiceRequest], - Awaitable[gcs_service.Service]]: - r"""Return a callable for the create service method over gRPC. - - Creates a service, and returns the new Service. - - Returns: - Callable[[~.CreateServiceRequest], - Awaitable[~.Service]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_service' not in self._stubs: - self._stubs['create_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/CreateService', - request_serializer=registration_service.CreateServiceRequest.serialize, - response_deserializer=gcs_service.Service.deserialize, - ) - return self._stubs['create_service'] - - @property - def list_services(self) -> Callable[ - [registration_service.ListServicesRequest], - Awaitable[registration_service.ListServicesResponse]]: - r"""Return a callable for the list services method over gRPC. - - Lists all services belonging to a namespace. - - Returns: - Callable[[~.ListServicesRequest], - Awaitable[~.ListServicesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_services' not in self._stubs: - self._stubs['list_services'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/ListServices', - request_serializer=registration_service.ListServicesRequest.serialize, - response_deserializer=registration_service.ListServicesResponse.deserialize, - ) - return self._stubs['list_services'] - - @property - def get_service(self) -> Callable[ - [registration_service.GetServiceRequest], - Awaitable[service.Service]]: - r"""Return a callable for the get service method over gRPC. - - Gets a service. - - Returns: - Callable[[~.GetServiceRequest], - Awaitable[~.Service]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_service' not in self._stubs: - self._stubs['get_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/GetService', - request_serializer=registration_service.GetServiceRequest.serialize, - response_deserializer=service.Service.deserialize, - ) - return self._stubs['get_service'] - - @property - def update_service(self) -> Callable[ - [registration_service.UpdateServiceRequest], - Awaitable[gcs_service.Service]]: - r"""Return a callable for the update service method over gRPC. - - Updates a service. - - Returns: - Callable[[~.UpdateServiceRequest], - Awaitable[~.Service]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_service' not in self._stubs: - self._stubs['update_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/UpdateService', - request_serializer=registration_service.UpdateServiceRequest.serialize, - response_deserializer=gcs_service.Service.deserialize, - ) - return self._stubs['update_service'] - - @property - def delete_service(self) -> Callable[ - [registration_service.DeleteServiceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete service method over gRPC. - - Deletes a service. This also deletes all endpoints - associated with the service. - - Returns: - Callable[[~.DeleteServiceRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_service' not in self._stubs: - self._stubs['delete_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/DeleteService', - request_serializer=registration_service.DeleteServiceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_service'] - - @property - def create_endpoint(self) -> Callable[ - [registration_service.CreateEndpointRequest], - Awaitable[gcs_endpoint.Endpoint]]: - r"""Return a callable for the create endpoint method over gRPC. - - Creates a endpoint, and returns the new Endpoint. - - Returns: - Callable[[~.CreateEndpointRequest], - Awaitable[~.Endpoint]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['create_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/CreateEndpoint', - request_serializer=registration_service.CreateEndpointRequest.serialize, - response_deserializer=gcs_endpoint.Endpoint.deserialize, - ) - return self._stubs['create_endpoint'] - - @property - def list_endpoints(self) -> Callable[ - [registration_service.ListEndpointsRequest], - Awaitable[registration_service.ListEndpointsResponse]]: - r"""Return a callable for the list endpoints method over gRPC. - - Lists all endpoints. - - Returns: - Callable[[~.ListEndpointsRequest], - Awaitable[~.ListEndpointsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoints' not in self._stubs: - self._stubs['list_endpoints'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/ListEndpoints', - request_serializer=registration_service.ListEndpointsRequest.serialize, - response_deserializer=registration_service.ListEndpointsResponse.deserialize, - ) - return self._stubs['list_endpoints'] - - @property - def get_endpoint(self) -> Callable[ - [registration_service.GetEndpointRequest], - Awaitable[endpoint.Endpoint]]: - r"""Return a callable for the get endpoint method over gRPC. - - Gets a endpoint. - - Returns: - Callable[[~.GetEndpointRequest], - Awaitable[~.Endpoint]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['get_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/GetEndpoint', - request_serializer=registration_service.GetEndpointRequest.serialize, - response_deserializer=endpoint.Endpoint.deserialize, - ) - return self._stubs['get_endpoint'] - - @property - def update_endpoint(self) -> Callable[ - [registration_service.UpdateEndpointRequest], - Awaitable[gcs_endpoint.Endpoint]]: - r"""Return a callable for the update endpoint method over gRPC. - - Updates a endpoint. - - Returns: - Callable[[~.UpdateEndpointRequest], - Awaitable[~.Endpoint]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['update_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/UpdateEndpoint', - request_serializer=registration_service.UpdateEndpointRequest.serialize, - response_deserializer=gcs_endpoint.Endpoint.deserialize, - ) - return self._stubs['update_endpoint'] - - @property - def delete_endpoint(self) -> Callable[ - [registration_service.DeleteEndpointRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete endpoint method over gRPC. - - Deletes a endpoint. - - Returns: - Callable[[~.DeleteEndpointRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_endpoint' not in self._stubs: - self._stubs['delete_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1.RegistrationService/DeleteEndpoint', - request_serializer=registration_service.DeleteEndpointRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_endpoint'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM Policy for a resource (namespace or - service only). - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.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.cloud.servicedirectory.v1.RegistrationService/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the IAM Policy for a resource (namespace or - service only). - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.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.cloud.servicedirectory.v1.RegistrationService/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Tests IAM permissions for a resource (namespace or - service only). - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.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.cloud.servicedirectory.v1.RegistrationService/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'RegistrationServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/__init__.py deleted file mode 100644 index acf22489..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/__init__.py +++ /dev/null @@ -1,74 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .endpoint import ( - Endpoint, -) -from .lookup_service import ( - ResolveServiceRequest, - ResolveServiceResponse, -) -from .namespace import ( - Namespace, -) -from .registration_service import ( - CreateEndpointRequest, - CreateNamespaceRequest, - CreateServiceRequest, - DeleteEndpointRequest, - DeleteNamespaceRequest, - DeleteServiceRequest, - GetEndpointRequest, - GetNamespaceRequest, - GetServiceRequest, - ListEndpointsRequest, - ListEndpointsResponse, - ListNamespacesRequest, - ListNamespacesResponse, - ListServicesRequest, - ListServicesResponse, - UpdateEndpointRequest, - UpdateNamespaceRequest, - UpdateServiceRequest, -) -from .service import ( - Service, -) - -__all__ = ( - 'Endpoint', - 'ResolveServiceRequest', - 'ResolveServiceResponse', - 'Namespace', - 'CreateEndpointRequest', - 'CreateNamespaceRequest', - 'CreateServiceRequest', - 'DeleteEndpointRequest', - 'DeleteNamespaceRequest', - 'DeleteServiceRequest', - 'GetEndpointRequest', - 'GetNamespaceRequest', - 'GetServiceRequest', - 'ListEndpointsRequest', - 'ListEndpointsResponse', - 'ListNamespacesRequest', - 'ListNamespacesResponse', - 'ListServicesRequest', - 'ListServicesResponse', - 'UpdateEndpointRequest', - 'UpdateNamespaceRequest', - 'UpdateServiceRequest', - 'Service', -) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/endpoint.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/endpoint.py deleted file mode 100644 index 20801a22..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/endpoint.py +++ /dev/null @@ -1,90 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.servicedirectory.v1', - manifest={ - 'Endpoint', - }, -) - - -class Endpoint(proto.Message): - r"""An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1.Service]. The service - must already exist to create an endpoint. - - Attributes: - name (str): - Immutable. The resource name for the endpoint in the format - 'projects/*/locations/*/namespaces/*/services/*/endpoints/*'. - address (str): - Optional. An IPv4 or IPv6 address. Service Directory will - reject bad addresses like: "8.8.8" "8.8.8.8:53" - "test:bad:address" "[::1]" "[::1]:8080" Limited to 45 - characters. - port (int): - Optional. Service Directory will reject values outside of - [0, 65535]. - annotations (Sequence[google.cloud.servicedirectory_v1.types.Endpoint.AnnotationsEntry]): - Optional. Annotations for the endpoint. This data can be - consumed by service clients. Restrictions: - - - The entire annotations dictionary may contain up to 512 - characters, spread accoss all key-value pairs. - Annotations that goes beyond any these limits will be - rejected. - - Valid annotation keys have two segments: an optional - prefix and name, separated by a slash (/). The name - segment is required and must be 63 characters or less, - beginning and ending with an alphanumeric character - ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), - and alphanumerics between. The prefix is optional. If - specified, the prefix must be a DNS subdomain: a series - of DNS labels separated by dots (.), not longer than 253 - characters in total, followed by a slash (/). Annotations - that fails to meet these requirements will be rejected. - - The '(*.)google.com/' and '(*.)googleapis.com/' prefixes - are reserved for system annotations managed by Service - Directory. If the user tries to write to these keyspaces, - those entries will be silently ignored by the system. - Note: This field is equivalent to the 'metadata' field in - the v1beta1 API. They have the same syntax and read/write - to the same location in Service Directory. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - address = proto.Field( - proto.STRING, - number=2, - ) - port = proto.Field( - proto.INT32, - number=3, - ) - annotations = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/lookup_service.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/lookup_service.py deleted file mode 100644 index 0f148f70..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/lookup_service.py +++ /dev/null @@ -1,95 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.cloud.servicedirectory_v1.types import service as gcs_service - - -__protobuf__ = proto.module( - package='google.cloud.servicedirectory.v1', - manifest={ - 'ResolveServiceRequest', - 'ResolveServiceResponse', - }, -) - - -class ResolveServiceRequest(proto.Message): - r"""The request message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. - Looks up a service by its name, returns the service and its - endpoints. - - Attributes: - name (str): - Required. The name of the service to resolve. - max_endpoints (int): - Optional. The maximum number of endpoints to - return. Defaults to 25. Maximum is 100. If a - value less than one is specified, the Default is - used. If a value greater than the Maximum is - specified, the Maximum is used. - endpoint_filter (str): - Optional. The filter applied to the endpoints of the - resolved service. - - General filter string syntax: () can be "name" or - "metadata." for map field. can be "<, >, <=, >=, !=, =, :". - Of which ":" means HAS and is roughly the same as "=". must - be the same data type as the field. can be "AND, OR, NOT". - - Examples of valid filters: - - - "metadata.owner" returns Endpoints that have a label with - the key "owner", this is the same as "metadata:owner" - - "metadata.protocol=gRPC" returns Endpoints that have - key/value "protocol=gRPC" - - "metadata.owner!=sd AND metadata.foo=bar" returns - Endpoints that have "owner" field in metadata with a - value that is not "sd" AND have the key/value foo=bar. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - max_endpoints = proto.Field( - proto.INT32, - number=2, - ) - endpoint_filter = proto.Field( - proto.STRING, - number=3, - ) - - -class ResolveServiceResponse(proto.Message): - r"""The response message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. - - Attributes: - service (google.cloud.servicedirectory_v1.types.Service): - - """ - - service = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_service.Service, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/namespace.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/namespace.py deleted file mode 100644 index f6c0fb5a..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/namespace.py +++ /dev/null @@ -1,55 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.servicedirectory.v1', - manifest={ - 'Namespace', - }, -) - - -class Namespace(proto.Message): - r"""A container for - [services][google.cloud.servicedirectory.v1.Service]. Namespaces - allow administrators to group services together and define - permissions for a collection of services. - - Attributes: - name (str): - Immutable. The resource name for the namespace in the format - 'projects/*/locations/*/namespaces/*'. - labels (Sequence[google.cloud.servicedirectory_v1.types.Namespace.LabelsEntry]): - Optional. Resource labels associated with - this Namespace. No more than 64 user labels can - be associated with a given resource. Label keys - and values can be no longer than 63 characters. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/registration_service.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/registration_service.py deleted file mode 100644 index 76d1511f..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/registration_service.py +++ /dev/null @@ -1,614 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1.types import service as gcs_service -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.servicedirectory.v1', - manifest={ - 'CreateNamespaceRequest', - 'ListNamespacesRequest', - 'ListNamespacesResponse', - 'GetNamespaceRequest', - 'UpdateNamespaceRequest', - 'DeleteNamespaceRequest', - 'CreateServiceRequest', - 'ListServicesRequest', - 'ListServicesResponse', - 'GetServiceRequest', - 'UpdateServiceRequest', - 'DeleteServiceRequest', - 'CreateEndpointRequest', - 'ListEndpointsRequest', - 'ListEndpointsResponse', - 'GetEndpointRequest', - 'UpdateEndpointRequest', - 'DeleteEndpointRequest', - }, -) - - -class CreateNamespaceRequest(proto.Message): - r"""The request message for - [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1.RegistrationService.CreateNamespace]. - - Attributes: - parent (str): - Required. The resource name of the project - and location the namespace will be created in. - namespace_id (str): - Required. The Resource ID must be 1-63 characters long, and - comply with RFC1035. Specifically, the name must be 1-63 - characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first - character must be a lowercase letter, and all following - characters must be a dash, lowercase letter, or digit, - except the last character, which cannot be a dash. - namespace (google.cloud.servicedirectory_v1.types.Namespace): - Required. A namespace with initial fields - set. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - namespace_id = proto.Field( - proto.STRING, - number=2, - ) - namespace = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_namespace.Namespace, - ) - - -class ListNamespacesRequest(proto.Message): - r"""The request message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. - - Attributes: - parent (str): - Required. The resource name of the project - and location whose namespaces we'd like to list. - page_size (int): - Optional. The maximum number of items to - return. - page_token (str): - Optional. The next_page_token value returned from a previous - List request, if any. - filter (str): - Optional. The filter to list result by. - - General filter string syntax: () can be "name", or "labels." - for map field. can be "<, >, <=, >=, !=, =, :". Of which ":" - means HAS, and is roughly the same as "=". must be the same - data type as field. can be "AND, OR, NOT". - - Examples of valid filters: - - - "labels.owner" returns Namespaces that have a label with - the key "owner" this is the same as "labels:owner". - - "labels.protocol=gRPC" returns Namespaces that have - key/value "protocol=gRPC". - - "name>projects/my-project/locations/us-east/namespaces/namespace-c" - returns Namespaces that have name that is alphabetically - later than the string, so "namespace-e" will be returned - but "namespace-a" will not be. - - "labels.owner!=sd AND labels.foo=bar" returns Namespaces - that have "owner" in label key but value is not "sd" AND - have key/value foo=bar. - - "doesnotexist.foo=bar" returns an empty list. Note that - Namespace doesn't have a field called "doesnotexist". - Since the filter does not match any Namespaces, it - returns no results. - order_by (str): - Optional. The order to list result by. - - General order by string syntax: () (,) allows - values {"name"} ascending or descending order by - . If this is left blank, "asc" is used. Note that an empty - order_by string result in default order, which is order by - name in ascending order. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - order_by = proto.Field( - proto.STRING, - number=5, - ) - - -class ListNamespacesResponse(proto.Message): - r"""The response message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. - - Attributes: - namespaces (Sequence[google.cloud.servicedirectory_v1.types.Namespace]): - The list of namespaces. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - namespaces = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_namespace.Namespace, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetNamespaceRequest(proto.Message): - r"""The request message for - [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1.RegistrationService.GetNamespace]. - - Attributes: - name (str): - Required. The name of the namespace to - retrieve. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateNamespaceRequest(proto.Message): - r"""The request message for - [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1.RegistrationService.UpdateNamespace]. - - Attributes: - namespace (google.cloud.servicedirectory_v1.types.Namespace): - Required. The updated namespace. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - namespace = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_namespace.Namespace, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteNamespaceRequest(proto.Message): - r"""The request message for - [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1.RegistrationService.DeleteNamespace]. - - Attributes: - name (str): - Required. The name of the namespace to - delete. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateServiceRequest(proto.Message): - r"""The request message for - [RegistrationService.CreateService][google.cloud.servicedirectory.v1.RegistrationService.CreateService]. - - Attributes: - parent (str): - Required. The resource name of the namespace - this service will belong to. - service_id (str): - Required. The Resource ID must be 1-63 characters long, and - comply with RFC1035. Specifically, the name must be 1-63 - characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first - character must be a lowercase letter, and all following - characters must be a dash, lowercase letter, or digit, - except the last character, which cannot be a dash. - service (google.cloud.servicedirectory_v1.types.Service): - Required. A service with initial fields set. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - service_id = proto.Field( - proto.STRING, - number=2, - ) - service = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_service.Service, - ) - - -class ListServicesRequest(proto.Message): - r"""The request message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. - - Attributes: - parent (str): - Required. The resource name of the namespace - whose services we'd like to list. - page_size (int): - Optional. The maximum number of items to - return. - page_token (str): - Optional. The next_page_token value returned from a previous - List request, if any. - filter (str): - Optional. The filter to list result by. - - General filter string syntax: () can be "name", or - "metadata." for map field. can be "<, >, <=, >=, !=, =, :". - Of which ":" means HAS, and is roughly the same as "=". must - be the same data type as field. can be "AND, OR, NOT". - - Examples of valid filters: - - - "metadata.owner" returns Services that have a label with - the key "owner" this is the same as "metadata:owner". - - "metadata.protocol=gRPC" returns Services that have - key/value "protocol=gRPC". - - "name>projects/my-project/locations/us-east/namespaces/my-namespace/services/service-c" - returns Services that have name that is alphabetically - later than the string, so "service-e" will be returned - but "service-a" will not be. - - "metadata.owner!=sd AND metadata.foo=bar" returns - Services that have "owner" in label key but value is not - "sd" AND have key/value foo=bar. - - "doesnotexist.foo=bar" returns an empty list. Note that - Service doesn't have a field called "doesnotexist". Since - the filter does not match any Services, it returns no - results. - order_by (str): - Optional. The order to list result by. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - order_by = proto.Field( - proto.STRING, - number=5, - ) - - -class ListServicesResponse(proto.Message): - r"""The response message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. - - Attributes: - services (Sequence[google.cloud.servicedirectory_v1.types.Service]): - The list of services. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - services = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_service.Service, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetServiceRequest(proto.Message): - r"""The request message for - [RegistrationService.GetService][google.cloud.servicedirectory.v1.RegistrationService.GetService]. - This should not be used for looking up a service. Insead, use the - ``resolve`` method as it will contain all endpoints and associated - metadata. - - Attributes: - name (str): - Required. The name of the service to get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateServiceRequest(proto.Message): - r"""The request message for - [RegistrationService.UpdateService][google.cloud.servicedirectory.v1.RegistrationService.UpdateService]. - - Attributes: - service (google.cloud.servicedirectory_v1.types.Service): - Required. The updated service. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - service = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_service.Service, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteServiceRequest(proto.Message): - r"""The request message for - [RegistrationService.DeleteService][google.cloud.servicedirectory.v1.RegistrationService.DeleteService]. - - Attributes: - name (str): - Required. The name of the service to delete. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateEndpointRequest(proto.Message): - r"""The request message for - [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.CreateEndpoint]. - - Attributes: - parent (str): - Required. The resource name of the service - that this endpoint provides. - endpoint_id (str): - Required. The Resource ID must be 1-63 characters long, and - comply with RFC1035. Specifically, the name must be 1-63 - characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first - character must be a lowercase letter, and all following - characters must be a dash, lowercase letter, or digit, - except the last character, which cannot be a dash. - endpoint (google.cloud.servicedirectory_v1.types.Endpoint): - Required. A endpoint with initial fields set. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - endpoint_id = proto.Field( - proto.STRING, - number=2, - ) - endpoint = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_endpoint.Endpoint, - ) - - -class ListEndpointsRequest(proto.Message): - r"""The request message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. - - Attributes: - parent (str): - Required. The resource name of the service - whose endpoints we'd like to list. - page_size (int): - Optional. The maximum number of items to - return. - page_token (str): - Optional. The next_page_token value returned from a previous - List request, if any. - filter (str): - Optional. The filter to list result by. - - General filter string syntax: () can be "name", "address", - "port" or "metadata." for map field. can be "<, >, <=, >=, - !=, =, :". Of which ":" means HAS, and is roughly the same - as "=". must be the same data type as field. can be "AND, - OR, NOT". - - Examples of valid filters: - - - "metadata.owner" returns Endpoints that have a label with - the key "owner" this is the same as "metadata:owner". - - "metadata.protocol=gRPC" returns Endpoints that have - key/value "protocol=gRPC". - - "address=192.108.1.105" returns Endpoints that have this - address. - - "port>8080" returns Endpoints that have port number - larger than 8080. - - "name>projects/my-project/locations/us-east/namespaces/my-namespace/services/my-service/endpoints/endpoint-c" - returns Endpoints that have name that is alphabetically - later than the string, so "endpoint-e" will be returned - but "endpoint-a" will not be. - - "metadata.owner!=sd AND metadata.foo=bar" returns - Endpoints that have "owner" in label key but value is not - "sd" AND have key/value foo=bar. - - "doesnotexist.foo=bar" returns an empty list. Note that - Endpoint doesn't have a field called "doesnotexist". - Since the filter does not match any Endpoints, it returns - no results. - order_by (str): - Optional. The order to list result by. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - order_by = proto.Field( - proto.STRING, - number=5, - ) - - -class ListEndpointsResponse(proto.Message): - r"""The response message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. - - Attributes: - endpoints (Sequence[google.cloud.servicedirectory_v1.types.Endpoint]): - The list of endpoints. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - endpoints = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_endpoint.Endpoint, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetEndpointRequest(proto.Message): - r"""The request message for - [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1.RegistrationService.GetEndpoint]. - This should not be used to lookup endpoints at runtime. Instead, use - the ``resolve`` method. - - Attributes: - name (str): - Required. The name of the endpoint to get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateEndpointRequest(proto.Message): - r"""The request message for - [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.UpdateEndpoint]. - - Attributes: - endpoint (google.cloud.servicedirectory_v1.types.Endpoint): - Required. The updated endpoint. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - endpoint = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_endpoint.Endpoint, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteEndpointRequest(proto.Message): - r"""The request message for - [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1.RegistrationService.DeleteEndpoint]. - - Attributes: - name (str): - Required. The name of the endpoint to delete. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/service.py b/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/service.py deleted file mode 100644 index ddbb594a..00000000 --- a/owl-bot-staging/v1/google/cloud/servicedirectory_v1/types/service.py +++ /dev/null @@ -1,87 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.cloud.servicedirectory_v1.types import endpoint - - -__protobuf__ = proto.module( - package='google.cloud.servicedirectory.v1', - manifest={ - 'Service', - }, -) - - -class Service(proto.Message): - r"""An individual service. A service contains a name and optional - metadata. A service must exist before - [endpoints][google.cloud.servicedirectory.v1.Endpoint] can be added - to it. - - Attributes: - name (str): - Immutable. The resource name for the service in the format - 'projects/*/locations/*/namespaces/*/services/*'. - annotations (Sequence[google.cloud.servicedirectory_v1.types.Service.AnnotationsEntry]): - Optional. Annotations for the service. This data can be - consumed by service clients. Restrictions: - - - The entire annotations dictionary may contain up to 2000 - characters, spread accoss all key-value pairs. - Annotations that goes beyond any these limits will be - rejected. - - Valid annotation keys have two segments: an optional - prefix and name, separated by a slash (/). The name - segment is required and must be 63 characters or less, - beginning and ending with an alphanumeric character - ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), - and alphanumerics between. The prefix is optional. If - specified, the prefix must be a DNS subdomain: a series - of DNS labels separated by dots (.), not longer than 253 - characters in total, followed by a slash (/). Annotations - that fails to meet these requirements will be rejected. - - The '(*.)google.com/' and '(*.)googleapis.com/' prefixes - are reserved for system annotations managed by Service - Directory. If the user tries to write to these keyspaces, - those entries will be silently ignored by the system. - Note: This field is equivalent to the 'metadata' field in - the v1beta1 API. They have the same syntax and read/write - to the same location in Service Directory. - endpoints (Sequence[google.cloud.servicedirectory_v1.types.Endpoint]): - Output only. Endpoints associated with this - service. Returned on LookupService.Resolve. - Control plane clients should use - RegistrationService.ListEndpoints. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - annotations = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - endpoints = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=endpoint.Endpoint, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 7706e4bc..00000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,132 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/servicedirectory_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - '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='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1/scripts/fixup_servicedirectory_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_servicedirectory_v1_keywords.py deleted file mode 100644 index 892e98cf..00000000 --- a/owl-bot-staging/v1/scripts/fixup_servicedirectory_v1_keywords.py +++ /dev/null @@ -1,194 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 servicedirectoryCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_endpoint': ('parent', 'endpoint_id', 'endpoint', ), - 'create_namespace': ('parent', 'namespace_id', 'namespace', ), - 'create_service': ('parent', 'service_id', 'service', ), - 'delete_endpoint': ('name', ), - 'delete_namespace': ('name', ), - 'delete_service': ('name', ), - 'get_endpoint': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_namespace': ('name', ), - 'get_service': ('name', ), - 'list_endpoints': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_namespaces': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_services': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'resolve_service': ('name', 'max_endpoints', 'endpoint_filter', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_endpoint': ('endpoint', 'update_mask', ), - 'update_namespace': ('namespace', 'update_mask', ), - 'update_service': ('service', 'update_mask', ), - } - - 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=servicedirectoryCallTransformer(), -): - """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 servicedirectory 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/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index f503a7fb..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,54 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 setuptools # type: ignore - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-servicedirectory', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1/tests/unit/gapic/servicedirectory_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py b/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py deleted file mode 100644 index 64c9100b..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py +++ /dev/null @@ -1,1157 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -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 path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.servicedirectory_v1.services.lookup_service import LookupServiceAsyncClient -from google.cloud.servicedirectory_v1.services.lookup_service import LookupServiceClient -from google.cloud.servicedirectory_v1.services.lookup_service import transports -from google.cloud.servicedirectory_v1.services.lookup_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.servicedirectory_v1.types import lookup_service -from google.cloud.servicedirectory_v1.types import service -from google.oauth2 import service_account -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert LookupServiceClient._get_default_mtls_endpoint(None) is None - assert LookupServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LookupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LookupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LookupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LookupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - LookupServiceClient, - LookupServiceAsyncClient, -]) -def test_lookup_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.LookupServiceGrpcTransport, "grpc"), - (transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_lookup_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", [ - LookupServiceClient, - LookupServiceAsyncClient, -]) -def test_lookup_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -def test_lookup_service_client_get_transport_class(): - transport = LookupServiceClient.get_transport_class() - available_transports = [ - transports.LookupServiceGrpcTransport, - ] - assert transport in available_transports - - transport = LookupServiceClient.get_transport_class("grpc") - assert transport == transports.LookupServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), - (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(LookupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceClient)) -@mock.patch.object(LookupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceAsyncClient)) -def test_lookup_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(LookupServiceClient, '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(LookupServiceClient, '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(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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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() - 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "true"), - (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "false"), - (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(LookupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceClient)) -@mock.patch.object(LookupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_lookup_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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - 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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), - (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_lookup_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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), - (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_lookup_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_lookup_service_client_client_options_from_dict(): - with mock.patch('google.cloud.servicedirectory_v1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = LookupServiceClient( - 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, - ) - - -def test_resolve_service(transport: str = 'grpc', request_type=lookup_service.ResolveServiceRequest): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resolve_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lookup_service.ResolveServiceResponse( - ) - response = client.resolve_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == lookup_service.ResolveServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, lookup_service.ResolveServiceResponse) - - -def test_resolve_service_from_dict(): - test_resolve_service(request_type=dict) - - -def test_resolve_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resolve_service), - '__call__') as call: - client.resolve_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == lookup_service.ResolveServiceRequest() - - -@pytest.mark.asyncio -async def test_resolve_service_async(transport: str = 'grpc_asyncio', request_type=lookup_service.ResolveServiceRequest): - client = LookupServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resolve_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lookup_service.ResolveServiceResponse( - )) - response = await client.resolve_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == lookup_service.ResolveServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, lookup_service.ResolveServiceResponse) - - -@pytest.mark.asyncio -async def test_resolve_service_async_from_dict(): - await test_resolve_service_async(request_type=dict) - - -def test_resolve_service_field_headers(): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = lookup_service.ResolveServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resolve_service), - '__call__') as call: - call.return_value = lookup_service.ResolveServiceResponse() - client.resolve_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_resolve_service_field_headers_async(): - client = LookupServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = lookup_service.ResolveServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resolve_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lookup_service.ResolveServiceResponse()) - await client.resolve_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LookupServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LookupServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LookupServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LookupServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.LookupServiceGrpcTransport, - transports.LookupServiceGrpcAsyncIOTransport, -]) -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_grpc_default(): - # A client should use the gRPC transport by default. - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LookupServiceGrpcTransport, - ) - -def test_lookup_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LookupServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_lookup_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.LookupServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'resolve_service', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -@requires_google_auth_gte_1_25_0 -def test_lookup_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.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LookupServiceTransport( - 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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_lookup_service_base_transport_with_credentials_file_old_google_auth(): - # 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.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LookupServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_lookup_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.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LookupServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_lookup_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) - LookupServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_lookup_service_auth_adc_old_google_auth(): - # 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) - LookupServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LookupServiceGrpcTransport, - transports.LookupServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_lookup_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.LookupServiceGrpcTransport, - transports.LookupServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_lookup_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LookupServiceGrpcTransport, grpc_helpers), - (transports.LookupServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_lookup_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( - "servicedirectory.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="servicedirectory.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) -def test_lookup_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_lookup_service_host_no_port(): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com'), - ) - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -def test_lookup_service_host_with_port(): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com:8000'), - ) - assert client.transport._host == 'servicedirectory.googleapis.com:8000' - -def test_lookup_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LookupServiceGrpcTransport( - 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_lookup_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LookupServiceGrpcAsyncIOTransport( - 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.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) -def test_lookup_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.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) -def test_lookup_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_endpoint_path(): - project = "squid" - location = "clam" - namespace = "whelk" - service = "octopus" - endpoint = "oyster" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) - actual = LookupServiceClient.endpoint_path(project, location, namespace, service, endpoint) - assert expected == actual - - -def test_parse_endpoint_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "namespace": "mussel", - "service": "winkle", - "endpoint": "nautilus", - } - path = LookupServiceClient.endpoint_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_endpoint_path(path) - assert expected == actual - -def test_service_path(): - project = "scallop" - location = "abalone" - namespace = "squid" - service = "clam" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - actual = LookupServiceClient.service_path(project, location, namespace, service) - assert expected == actual - - -def test_parse_service_path(): - expected = { - "project": "whelk", - "location": "octopus", - "namespace": "oyster", - "service": "nudibranch", - } - path = LookupServiceClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_service_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = LookupServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = LookupServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = LookupServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = LookupServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = LookupServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = LookupServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = LookupServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = LookupServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = LookupServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = LookupServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.LookupServiceTransport, '_prep_wrapped_messages') as prep: - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.LookupServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = LookupServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = LookupServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = LookupServiceClient( - 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() diff --git a/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_registration_service.py b/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_registration_service.py deleted file mode 100644 index 5ae52c56..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/servicedirectory_v1/test_registration_service.py +++ /dev/null @@ -1,5654 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -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 path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.servicedirectory_v1.services.registration_service import RegistrationServiceAsyncClient -from google.cloud.servicedirectory_v1.services.registration_service import RegistrationServiceClient -from google.cloud.servicedirectory_v1.services.registration_service import pagers -from google.cloud.servicedirectory_v1.services.registration_service import transports -from google.cloud.servicedirectory_v1.services.registration_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.servicedirectory_v1.types import endpoint -from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1.types import namespace -from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1.types import registration_service -from google.cloud.servicedirectory_v1.types import service -from google.cloud.servicedirectory_v1.types import service as gcs_service -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.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert RegistrationServiceClient._get_default_mtls_endpoint(None) is None - assert RegistrationServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RegistrationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RegistrationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RegistrationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RegistrationServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - RegistrationServiceClient, - RegistrationServiceAsyncClient, -]) -def test_registration_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RegistrationServiceGrpcTransport, "grpc"), - (transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_registration_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", [ - RegistrationServiceClient, - RegistrationServiceAsyncClient, -]) -def test_registration_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -def test_registration_service_client_get_transport_class(): - transport = RegistrationServiceClient.get_transport_class() - available_transports = [ - transports.RegistrationServiceGrpcTransport, - ] - assert transport in available_transports - - transport = RegistrationServiceClient.get_transport_class("grpc") - assert transport == transports.RegistrationServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), - (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(RegistrationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceClient)) -@mock.patch.object(RegistrationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceAsyncClient)) -def test_registration_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(RegistrationServiceClient, '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(RegistrationServiceClient, '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(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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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() - 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc", "true"), - (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc", "false"), - (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(RegistrationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceClient)) -@mock.patch.object(RegistrationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_registration_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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - 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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), - (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_registration_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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), - (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_registration_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_registration_service_client_client_options_from_dict(): - with mock.patch('google.cloud.servicedirectory_v1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RegistrationServiceClient( - 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, - ) - - -def test_create_namespace(transport: str = 'grpc', request_type=registration_service.CreateNamespaceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace( - name='name_value', - ) - response = client.create_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_namespace.Namespace) - assert response.name == 'name_value' - - -def test_create_namespace_from_dict(): - test_create_namespace(request_type=dict) - - -def test_create_namespace_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_namespace), - '__call__') as call: - client.create_namespace() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateNamespaceRequest() - - -@pytest.mark.asyncio -async def test_create_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateNamespaceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace( - name='name_value', - )) - response = await client.create_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_namespace.Namespace) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_namespace_async_from_dict(): - await test_create_namespace_async(request_type=dict) - - -def test_create_namespace_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateNamespaceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_namespace), - '__call__') as call: - call.return_value = gcs_namespace.Namespace() - client.create_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_namespace_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateNamespaceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_namespace), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) - await client.create_namespace(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_namespace_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_namespace( - parent='parent_value', - namespace=gcs_namespace.Namespace(name='name_value'), - namespace_id='namespace_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].namespace == gcs_namespace.Namespace(name='name_value') - assert args[0].namespace_id == 'namespace_id_value' - - -def test_create_namespace_flattened_error(): - client = RegistrationServiceClient( - 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_namespace( - registration_service.CreateNamespaceRequest(), - parent='parent_value', - namespace=gcs_namespace.Namespace(name='name_value'), - namespace_id='namespace_id_value', - ) - - -@pytest.mark.asyncio -async def test_create_namespace_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_namespace( - parent='parent_value', - namespace=gcs_namespace.Namespace(name='name_value'), - namespace_id='namespace_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].namespace == gcs_namespace.Namespace(name='name_value') - assert args[0].namespace_id == 'namespace_id_value' - - -@pytest.mark.asyncio -async def test_create_namespace_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_namespace( - registration_service.CreateNamespaceRequest(), - parent='parent_value', - namespace=gcs_namespace.Namespace(name='name_value'), - namespace_id='namespace_id_value', - ) - - -def test_list_namespaces(transport: str = 'grpc', request_type=registration_service.ListNamespacesRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespaces), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListNamespacesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_namespaces(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListNamespacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNamespacesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_namespaces_from_dict(): - test_list_namespaces(request_type=dict) - - -def test_list_namespaces_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - client.list_namespaces() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListNamespacesRequest() - - -@pytest.mark.asyncio -async def test_list_namespaces_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListNamespacesRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespaces), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_namespaces(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListNamespacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNamespacesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_namespaces_async_from_dict(): - await test_list_namespaces_async(request_type=dict) - - -def test_list_namespaces_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListNamespacesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - call.return_value = registration_service.ListNamespacesResponse() - client.list_namespaces(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_namespaces_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListNamespacesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse()) - await client.list_namespaces(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_namespaces_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListNamespacesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_namespaces( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_namespaces_flattened_error(): - client = RegistrationServiceClient( - 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_namespaces( - registration_service.ListNamespacesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_namespaces_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListNamespacesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_namespaces( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_namespaces_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_namespaces( - registration_service.ListNamespacesRequest(), - parent='parent_value', - ) - - -def test_list_namespaces_pager(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - namespace.Namespace(), - ], - next_page_token='abc', - ), - registration_service.ListNamespacesResponse( - namespaces=[], - next_page_token='def', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - ], - next_page_token='ghi', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_namespaces(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, namespace.Namespace) - for i in results) - -def test_list_namespaces_pages(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - namespace.Namespace(), - ], - next_page_token='abc', - ), - registration_service.ListNamespacesResponse( - namespaces=[], - next_page_token='def', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - ], - next_page_token='ghi', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - ], - ), - RuntimeError, - ) - pages = list(client.list_namespaces(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_namespaces_async_pager(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - namespace.Namespace(), - ], - next_page_token='abc', - ), - registration_service.ListNamespacesResponse( - namespaces=[], - next_page_token='def', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - ], - next_page_token='ghi', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_namespaces(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, namespace.Namespace) - for i in responses) - -@pytest.mark.asyncio -async def test_list_namespaces_async_pages(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - namespace.Namespace(), - ], - next_page_token='abc', - ), - registration_service.ListNamespacesResponse( - namespaces=[], - next_page_token='def', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - ], - next_page_token='ghi', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_namespaces(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_namespace(transport: str = 'grpc', request_type=registration_service.GetNamespaceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = namespace.Namespace( - name='name_value', - ) - response = client.get_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, namespace.Namespace) - assert response.name == 'name_value' - - -def test_get_namespace_from_dict(): - test_get_namespace(request_type=dict) - - -def test_get_namespace_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespace), - '__call__') as call: - client.get_namespace() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetNamespaceRequest() - - -@pytest.mark.asyncio -async def test_get_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetNamespaceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace( - name='name_value', - )) - response = await client.get_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, namespace.Namespace) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_namespace_async_from_dict(): - await test_get_namespace_async(request_type=dict) - - -def test_get_namespace_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetNamespaceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespace), - '__call__') as call: - call.return_value = namespace.Namespace() - client.get_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_namespace_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetNamespaceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespace), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) - await client.get_namespace(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_namespace_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = namespace.Namespace() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_namespace( - 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] - assert args[0].name == 'name_value' - - -def test_get_namespace_flattened_error(): - client = RegistrationServiceClient( - 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_namespace( - registration_service.GetNamespaceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_namespace_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = namespace.Namespace() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_namespace( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_namespace_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_namespace( - registration_service.GetNamespaceRequest(), - name='name_value', - ) - - -def test_update_namespace(transport: str = 'grpc', request_type=registration_service.UpdateNamespaceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace( - name='name_value', - ) - response = client.update_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_namespace.Namespace) - assert response.name == 'name_value' - - -def test_update_namespace_from_dict(): - test_update_namespace(request_type=dict) - - -def test_update_namespace_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_namespace), - '__call__') as call: - client.update_namespace() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateNamespaceRequest() - - -@pytest.mark.asyncio -async def test_update_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateNamespaceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace( - name='name_value', - )) - response = await client.update_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_namespace.Namespace) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_namespace_async_from_dict(): - await test_update_namespace_async(request_type=dict) - - -def test_update_namespace_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateNamespaceRequest() - - request.namespace.name = 'namespace.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_namespace), - '__call__') as call: - call.return_value = gcs_namespace.Namespace() - client.update_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'namespace.name=namespace.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_namespace_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateNamespaceRequest() - - request.namespace.name = 'namespace.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_namespace), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) - await client.update_namespace(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', - 'namespace.name=namespace.name/value', - ) in kw['metadata'] - - -def test_update_namespace_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_namespace( - namespace=gcs_namespace.Namespace(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].namespace == gcs_namespace.Namespace(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_namespace_flattened_error(): - client = RegistrationServiceClient( - 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_namespace( - registration_service.UpdateNamespaceRequest(), - namespace=gcs_namespace.Namespace(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_namespace_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_namespace( - namespace=gcs_namespace.Namespace(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].namespace == gcs_namespace.Namespace(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_namespace_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_namespace( - registration_service.UpdateNamespaceRequest(), - namespace=gcs_namespace.Namespace(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_namespace(transport: str = 'grpc', request_type=registration_service.DeleteNamespaceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteNamespaceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_namespace_from_dict(): - test_delete_namespace(request_type=dict) - - -def test_delete_namespace_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_namespace), - '__call__') as call: - client.delete_namespace() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteNamespaceRequest() - - -@pytest.mark.asyncio -async def test_delete_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteNamespaceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteNamespaceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_namespace_async_from_dict(): - await test_delete_namespace_async(request_type=dict) - - -def test_delete_namespace_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteNamespaceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_namespace), - '__call__') as call: - call.return_value = None - client.delete_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_namespace_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteNamespaceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_namespace), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_namespace(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_namespace_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_namespace( - 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] - assert args[0].name == 'name_value' - - -def test_delete_namespace_flattened_error(): - client = RegistrationServiceClient( - 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_namespace( - registration_service.DeleteNamespaceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_namespace_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_namespace( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_namespace_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_namespace( - registration_service.DeleteNamespaceRequest(), - name='name_value', - ) - - -def test_create_service(transport: str = 'grpc', request_type=registration_service.CreateServiceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service( - name='name_value', - ) - response = client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_service.Service) - assert response.name == 'name_value' - - -def test_create_service_from_dict(): - test_create_service(request_type=dict) - - -def test_create_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - client.create_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateServiceRequest() - - -@pytest.mark.asyncio -async def test_create_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateServiceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service( - name='name_value', - )) - response = await client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_service.Service) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_service_async_from_dict(): - await test_create_service_async(request_type=dict) - - -def test_create_service_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateServiceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - call.return_value = gcs_service.Service() - client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_service_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateServiceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) - await client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_create_service_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_service( - parent='parent_value', - service=gcs_service.Service(name='name_value'), - service_id='service_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].service == gcs_service.Service(name='name_value') - assert args[0].service_id == 'service_id_value' - - -def test_create_service_flattened_error(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_service( - registration_service.CreateServiceRequest(), - parent='parent_value', - service=gcs_service.Service(name='name_value'), - service_id='service_id_value', - ) - - -@pytest.mark.asyncio -async def test_create_service_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_service( - parent='parent_value', - service=gcs_service.Service(name='name_value'), - service_id='service_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].service == gcs_service.Service(name='name_value') - assert args[0].service_id == 'service_id_value' - - -@pytest.mark.asyncio -async def test_create_service_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_service( - registration_service.CreateServiceRequest(), - parent='parent_value', - service=gcs_service.Service(name='name_value'), - service_id='service_id_value', - ) - - -def test_list_services(transport: str = 'grpc', request_type=registration_service.ListServicesRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListServicesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListServicesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_services_from_dict(): - test_list_services(request_type=dict) - - -def test_list_services_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - client.list_services() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListServicesRequest() - - -@pytest.mark.asyncio -async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListServicesRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListServicesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_services_async_from_dict(): - await test_list_services_async(request_type=dict) - - -def test_list_services_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListServicesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - call.return_value = registration_service.ListServicesResponse() - client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_services_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListServicesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse()) - await client.list_services(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_services_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListServicesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_services( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_services_flattened_error(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_services( - registration_service.ListServicesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_services_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListServicesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_services( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_services_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_services( - registration_service.ListServicesRequest(), - parent='parent_value', - ) - - -def test_list_services_pager(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - registration_service.ListServicesResponse( - services=[], - next_page_token='def', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_services(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, service.Service) - for i in results) - -def test_list_services_pages(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - registration_service.ListServicesResponse( - services=[], - next_page_token='def', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - pages = list(client.list_services(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_services_async_pager(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - registration_service.ListServicesResponse( - services=[], - next_page_token='def', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_services(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, service.Service) - for i in responses) - -@pytest.mark.asyncio -async def test_list_services_async_pages(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - registration_service.ListServicesResponse( - services=[], - next_page_token='def', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_services(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_service(transport: str = 'grpc', request_type=registration_service.GetServiceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.Service( - name='name_value', - ) - response = client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == 'name_value' - - -def test_get_service_from_dict(): - test_get_service(request_type=dict) - - -def test_get_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - client.get_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetServiceRequest() - - -@pytest.mark.asyncio -async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetServiceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.Service( - name='name_value', - )) - response = await client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_service_async_from_dict(): - await test_get_service_async(request_type=dict) - - -def test_get_service_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - call.return_value = service.Service() - client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_service_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) - await client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_service_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.Service() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_service( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_service_flattened_error(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_service( - registration_service.GetServiceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_service_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.Service() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_service( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_service_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_service( - registration_service.GetServiceRequest(), - name='name_value', - ) - - -def test_update_service(transport: str = 'grpc', request_type=registration_service.UpdateServiceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service( - name='name_value', - ) - response = client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_service.Service) - assert response.name == 'name_value' - - -def test_update_service_from_dict(): - test_update_service(request_type=dict) - - -def test_update_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - client.update_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateServiceRequest() - - -@pytest.mark.asyncio -async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateServiceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service( - name='name_value', - )) - response = await client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_service.Service) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_service_async_from_dict(): - await test_update_service_async(request_type=dict) - - -def test_update_service_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateServiceRequest() - - request.service.name = 'service.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - call.return_value = gcs_service.Service() - client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service.name=service.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_service_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateServiceRequest() - - request.service.name = 'service.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) - await client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service.name=service.name/value', - ) in kw['metadata'] - - -def test_update_service_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_service( - service=gcs_service.Service(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].service == gcs_service.Service(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_service_flattened_error(): - client = RegistrationServiceClient( - 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_service( - registration_service.UpdateServiceRequest(), - service=gcs_service.Service(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_service_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_service( - service=gcs_service.Service(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].service == gcs_service.Service(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_service_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_service( - registration_service.UpdateServiceRequest(), - service=gcs_service.Service(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_service(transport: str = 'grpc', request_type=registration_service.DeleteServiceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteServiceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_service_from_dict(): - test_delete_service(request_type=dict) - - -def test_delete_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - client.delete_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteServiceRequest() - - -@pytest.mark.asyncio -async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteServiceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteServiceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_service_async_from_dict(): - await test_delete_service_async(request_type=dict) - - -def test_delete_service_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - call.return_value = None - client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_service_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_service_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_service( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_delete_service_flattened_error(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_service( - registration_service.DeleteServiceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_service_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_service( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_service_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_service( - registration_service.DeleteServiceRequest(), - name='name_value', - ) - - -def test_create_endpoint(transport: str = 'grpc', request_type=registration_service.CreateEndpointRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - ) - response = client.create_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - - -def test_create_endpoint_from_dict(): - test_create_endpoint(request_type=dict) - - -def test_create_endpoint_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint), - '__call__') as call: - client.create_endpoint() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateEndpointRequest() - - -@pytest.mark.asyncio -async def test_create_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateEndpointRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - )) - response = await client.create_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - - -@pytest.mark.asyncio -async def test_create_endpoint_async_from_dict(): - await test_create_endpoint_async(request_type=dict) - - -def test_create_endpoint_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateEndpointRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint), - '__call__') as call: - call.return_value = gcs_endpoint.Endpoint() - client.create_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_endpoint_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateEndpointRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) - await client.create_endpoint(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_endpoint_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_endpoint( - parent='parent_value', - endpoint=gcs_endpoint.Endpoint(name='name_value'), - endpoint_id='endpoint_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') - assert args[0].endpoint_id == 'endpoint_id_value' - - -def test_create_endpoint_flattened_error(): - client = RegistrationServiceClient( - 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_endpoint( - registration_service.CreateEndpointRequest(), - parent='parent_value', - endpoint=gcs_endpoint.Endpoint(name='name_value'), - endpoint_id='endpoint_id_value', - ) - - -@pytest.mark.asyncio -async def test_create_endpoint_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_endpoint( - parent='parent_value', - endpoint=gcs_endpoint.Endpoint(name='name_value'), - endpoint_id='endpoint_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') - assert args[0].endpoint_id == 'endpoint_id_value' - - -@pytest.mark.asyncio -async def test_create_endpoint_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_endpoint( - registration_service.CreateEndpointRequest(), - parent='parent_value', - endpoint=gcs_endpoint.Endpoint(name='name_value'), - endpoint_id='endpoint_id_value', - ) - - -def test_list_endpoints(transport: str = 'grpc', request_type=registration_service.ListEndpointsRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoints), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListEndpointsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_endpoints(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListEndpointsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEndpointsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_endpoints_from_dict(): - test_list_endpoints(request_type=dict) - - -def test_list_endpoints_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - client.list_endpoints() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListEndpointsRequest() - - -@pytest.mark.asyncio -async def test_list_endpoints_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListEndpointsRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoints), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_endpoints(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListEndpointsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEndpointsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_endpoints_async_from_dict(): - await test_list_endpoints_async(request_type=dict) - - -def test_list_endpoints_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListEndpointsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - call.return_value = registration_service.ListEndpointsResponse() - client.list_endpoints(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_endpoints_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListEndpointsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse()) - await client.list_endpoints(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_endpoints_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListEndpointsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_endpoints( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_endpoints_flattened_error(): - client = RegistrationServiceClient( - 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_endpoints( - registration_service.ListEndpointsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_endpoints_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListEndpointsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_endpoints( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_endpoints_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_endpoints( - registration_service.ListEndpointsRequest(), - parent='parent_value', - ) - - -def test_list_endpoints_pager(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - next_page_token='abc', - ), - registration_service.ListEndpointsResponse( - endpoints=[], - next_page_token='def', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - ], - next_page_token='ghi', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_endpoints(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, endpoint.Endpoint) - for i in results) - -def test_list_endpoints_pages(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - next_page_token='abc', - ), - registration_service.ListEndpointsResponse( - endpoints=[], - next_page_token='def', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - ], - next_page_token='ghi', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - ), - RuntimeError, - ) - pages = list(client.list_endpoints(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_endpoints_async_pager(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - next_page_token='abc', - ), - registration_service.ListEndpointsResponse( - endpoints=[], - next_page_token='def', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - ], - next_page_token='ghi', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_endpoints(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, endpoint.Endpoint) - for i in responses) - -@pytest.mark.asyncio -async def test_list_endpoints_async_pages(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - next_page_token='abc', - ), - registration_service.ListEndpointsResponse( - endpoints=[], - next_page_token='def', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - ], - next_page_token='ghi', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_endpoints(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_endpoint(transport: str = 'grpc', request_type=registration_service.GetEndpointRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - ) - response = client.get_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - - -def test_get_endpoint_from_dict(): - test_get_endpoint(request_type=dict) - - -def test_get_endpoint_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint), - '__call__') as call: - client.get_endpoint() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetEndpointRequest() - - -@pytest.mark.asyncio -async def test_get_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetEndpointRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - )) - response = await client.get_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - - -@pytest.mark.asyncio -async def test_get_endpoint_async_from_dict(): - await test_get_endpoint_async(request_type=dict) - - -def test_get_endpoint_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetEndpointRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint), - '__call__') as call: - call.return_value = endpoint.Endpoint() - client.get_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_endpoint_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetEndpointRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) - await client.get_endpoint(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_endpoint_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint.Endpoint() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_endpoint( - 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] - assert args[0].name == 'name_value' - - -def test_get_endpoint_flattened_error(): - client = RegistrationServiceClient( - 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_endpoint( - registration_service.GetEndpointRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_endpoint_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint.Endpoint() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_endpoint( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_endpoint_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_endpoint( - registration_service.GetEndpointRequest(), - name='name_value', - ) - - -def test_update_endpoint(transport: str = 'grpc', request_type=registration_service.UpdateEndpointRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - ) - response = client.update_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - - -def test_update_endpoint_from_dict(): - test_update_endpoint(request_type=dict) - - -def test_update_endpoint_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint), - '__call__') as call: - client.update_endpoint() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateEndpointRequest() - - -@pytest.mark.asyncio -async def test_update_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateEndpointRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - )) - response = await client.update_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - - -@pytest.mark.asyncio -async def test_update_endpoint_async_from_dict(): - await test_update_endpoint_async(request_type=dict) - - -def test_update_endpoint_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateEndpointRequest() - - request.endpoint.name = 'endpoint.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint), - '__call__') as call: - call.return_value = gcs_endpoint.Endpoint() - client.update_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'endpoint.name=endpoint.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_endpoint_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateEndpointRequest() - - request.endpoint.name = 'endpoint.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) - await client.update_endpoint(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', - 'endpoint.name=endpoint.name/value', - ) in kw['metadata'] - - -def test_update_endpoint_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_endpoint( - endpoint=gcs_endpoint.Endpoint(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_endpoint_flattened_error(): - client = RegistrationServiceClient( - 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_endpoint( - registration_service.UpdateEndpointRequest(), - endpoint=gcs_endpoint.Endpoint(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_endpoint_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_endpoint( - endpoint=gcs_endpoint.Endpoint(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_endpoint_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_endpoint( - registration_service.UpdateEndpointRequest(), - endpoint=gcs_endpoint.Endpoint(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_endpoint(transport: str = 'grpc', request_type=registration_service.DeleteEndpointRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteEndpointRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_endpoint_from_dict(): - test_delete_endpoint(request_type=dict) - - -def test_delete_endpoint_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint), - '__call__') as call: - client.delete_endpoint() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteEndpointRequest() - - -@pytest.mark.asyncio -async def test_delete_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteEndpointRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteEndpointRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_endpoint_async_from_dict(): - await test_delete_endpoint_async(request_type=dict) - - -def test_delete_endpoint_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteEndpointRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint), - '__call__') as call: - call.return_value = None - client.delete_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_endpoint_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteEndpointRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_endpoint(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_endpoint_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_endpoint( - 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] - assert args[0].name == 'name_value' - - -def test_delete_endpoint_flattened_error(): - client = RegistrationServiceClient( - 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_endpoint( - registration_service.DeleteEndpointRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_endpoint_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_endpoint( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_endpoint_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_endpoint( - registration_service.DeleteEndpointRequest(), - name='name_value', - ) - - -def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - test_get_iam_policy(request_type=dict) - - -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = RegistrationServiceClient( - 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() - - -def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - test_set_iam_policy(request_type=dict) - - -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = RegistrationServiceClient( - 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() - - -def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - test_test_iam_permissions(request_type=dict) - - -def test_test_iam_permissions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = RegistrationServiceClient( - 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() - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegistrationServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegistrationServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RegistrationServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RegistrationServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RegistrationServiceGrpcTransport, - transports.RegistrationServiceGrpcAsyncIOTransport, -]) -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_grpc_default(): - # A client should use the gRPC transport by default. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RegistrationServiceGrpcTransport, - ) - -def test_registration_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RegistrationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_registration_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RegistrationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_namespace', - 'list_namespaces', - 'get_namespace', - 'update_namespace', - 'delete_namespace', - 'create_service', - 'list_services', - 'get_service', - 'update_service', - 'delete_service', - 'create_endpoint', - 'list_endpoints', - 'get_endpoint', - 'update_endpoint', - 'delete_endpoint', - 'get_iam_policy', - 'set_iam_policy', - 'test_iam_permissions', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -@requires_google_auth_gte_1_25_0 -def test_registration_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.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegistrationServiceTransport( - 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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_registration_service_base_transport_with_credentials_file_old_google_auth(): - # 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.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegistrationServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_registration_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.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegistrationServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_registration_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) - RegistrationServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_registration_service_auth_adc_old_google_auth(): - # 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) - RegistrationServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RegistrationServiceGrpcTransport, - transports.RegistrationServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_registration_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.RegistrationServiceGrpcTransport, - transports.RegistrationServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_registration_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.RegistrationServiceGrpcTransport, grpc_helpers), - (transports.RegistrationServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_registration_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( - "servicedirectory.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="servicedirectory.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) -def test_registration_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_registration_service_host_no_port(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com'), - ) - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -def test_registration_service_host_with_port(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com:8000'), - ) - assert client.transport._host == 'servicedirectory.googleapis.com:8000' - -def test_registration_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegistrationServiceGrpcTransport( - 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_registration_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegistrationServiceGrpcAsyncIOTransport( - 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.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) -def test_registration_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.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) -def test_registration_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_endpoint_path(): - project = "squid" - location = "clam" - namespace = "whelk" - service = "octopus" - endpoint = "oyster" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) - actual = RegistrationServiceClient.endpoint_path(project, location, namespace, service, endpoint) - assert expected == actual - - -def test_parse_endpoint_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "namespace": "mussel", - "service": "winkle", - "endpoint": "nautilus", - } - path = RegistrationServiceClient.endpoint_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_endpoint_path(path) - assert expected == actual - -def test_namespace_path(): - project = "scallop" - location = "abalone" - namespace = "squid" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}".format(project=project, location=location, namespace=namespace, ) - actual = RegistrationServiceClient.namespace_path(project, location, namespace) - assert expected == actual - - -def test_parse_namespace_path(): - expected = { - "project": "clam", - "location": "whelk", - "namespace": "octopus", - } - path = RegistrationServiceClient.namespace_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_namespace_path(path) - assert expected == actual - -def test_service_path(): - project = "oyster" - location = "nudibranch" - namespace = "cuttlefish" - service = "mussel" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - actual = RegistrationServiceClient.service_path(project, location, namespace, service) - assert expected == actual - - -def test_parse_service_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "namespace": "scallop", - "service": "abalone", - } - path = RegistrationServiceClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_service_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RegistrationServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = RegistrationServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = RegistrationServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = RegistrationServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RegistrationServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = RegistrationServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = RegistrationServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = RegistrationServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RegistrationServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = RegistrationServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.RegistrationServiceTransport, '_prep_wrapped_messages') as prep: - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RegistrationServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = RegistrationServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = RegistrationServiceClient( - 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() diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc deleted file mode 100644 index 078f9e0e..00000000 --- a/owl-bot-staging/v1beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/servicedirectory/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in deleted file mode 100644 index 1d83357d..00000000 --- a/owl-bot-staging/v1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/servicedirectory *.py -recursive-include google/cloud/servicedirectory_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst deleted file mode 100644 index 2a61473b..00000000 --- a/owl-bot-staging/v1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Servicedirectory 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 Servicedirectory 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py deleted file mode 100644 index c8721e6e..00000000 --- a/owl-bot-staging/v1beta1/docs/conf.py +++ /dev/null @@ -1,376 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-service-directory 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-service-directory" -copyright = u"2020, 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 = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-service-directory-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 = [ - ( - master_doc, - "google-cloud-service-directory.tex", - u"google-cloud-service-directory 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 = [ - ( - master_doc, - "google-cloud-service-directory", - u"Google Cloud Servicedirectory 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 = [ - ( - master_doc, - "google-cloud-service-directory", - u"google-cloud-service-directory Documentation", - author, - "google-cloud-service-directory", - "GAPIC library for Google Cloud Servicedirectory 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/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst deleted file mode 100644 index 3b2d48ec..00000000 --- a/owl-bot-staging/v1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - servicedirectory_v1beta1/services - servicedirectory_v1beta1/types diff --git a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/lookup_service.rst b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/lookup_service.rst deleted file mode 100644 index 787d8964..00000000 --- a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/lookup_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -LookupService -------------------------------- - -.. automodule:: google.cloud.servicedirectory_v1beta1.services.lookup_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/registration_service.rst b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/registration_service.rst deleted file mode 100644 index de5871e4..00000000 --- a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/registration_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -RegistrationService -------------------------------------- - -.. automodule:: google.cloud.servicedirectory_v1beta1.services.registration_service - :members: - :inherited-members: - -.. automodule:: google.cloud.servicedirectory_v1beta1.services.registration_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/services.rst deleted file mode 100644 index 359795b0..00000000 --- a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/services.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Servicedirectory v1beta1 API -====================================================== -.. toctree:: - :maxdepth: 2 - - lookup_service - registration_service diff --git a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/types.rst deleted file mode 100644 index 1a2daef4..00000000 --- a/owl-bot-staging/v1beta1/docs/servicedirectory_v1beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Servicedirectory v1beta1 API -=================================================== - -.. automodule:: google.cloud.servicedirectory_v1beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory/__init__.py deleted file mode 100644 index f6952a07..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory/__init__.py +++ /dev/null @@ -1,73 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.servicedirectory_v1beta1.services.lookup_service.client import LookupServiceClient -from google.cloud.servicedirectory_v1beta1.services.lookup_service.async_client import LookupServiceAsyncClient -from google.cloud.servicedirectory_v1beta1.services.registration_service.client import RegistrationServiceClient -from google.cloud.servicedirectory_v1beta1.services.registration_service.async_client import RegistrationServiceAsyncClient - -from google.cloud.servicedirectory_v1beta1.types.endpoint import Endpoint -from google.cloud.servicedirectory_v1beta1.types.lookup_service import ResolveServiceRequest -from google.cloud.servicedirectory_v1beta1.types.lookup_service import ResolveServiceResponse -from google.cloud.servicedirectory_v1beta1.types.namespace import Namespace -from google.cloud.servicedirectory_v1beta1.types.registration_service import CreateEndpointRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import CreateNamespaceRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import CreateServiceRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import DeleteEndpointRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import DeleteNamespaceRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import DeleteServiceRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import GetEndpointRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import GetNamespaceRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import GetServiceRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import ListEndpointsRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import ListEndpointsResponse -from google.cloud.servicedirectory_v1beta1.types.registration_service import ListNamespacesRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import ListNamespacesResponse -from google.cloud.servicedirectory_v1beta1.types.registration_service import ListServicesRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import ListServicesResponse -from google.cloud.servicedirectory_v1beta1.types.registration_service import UpdateEndpointRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import UpdateNamespaceRequest -from google.cloud.servicedirectory_v1beta1.types.registration_service import UpdateServiceRequest -from google.cloud.servicedirectory_v1beta1.types.service import Service - -__all__ = ('LookupServiceClient', - 'LookupServiceAsyncClient', - 'RegistrationServiceClient', - 'RegistrationServiceAsyncClient', - 'Endpoint', - 'ResolveServiceRequest', - 'ResolveServiceResponse', - 'Namespace', - 'CreateEndpointRequest', - 'CreateNamespaceRequest', - 'CreateServiceRequest', - 'DeleteEndpointRequest', - 'DeleteNamespaceRequest', - 'DeleteServiceRequest', - 'GetEndpointRequest', - 'GetNamespaceRequest', - 'GetServiceRequest', - 'ListEndpointsRequest', - 'ListEndpointsResponse', - 'ListNamespacesRequest', - 'ListNamespacesResponse', - 'ListServicesRequest', - 'ListServicesResponse', - 'UpdateEndpointRequest', - 'UpdateNamespaceRequest', - 'UpdateServiceRequest', - 'Service', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory/py.typed b/owl-bot-staging/v1beta1/google/cloud/servicedirectory/py.typed deleted file mode 100644 index 8a62d150..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-service-directory package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/__init__.py deleted file mode 100644 index 9160262b..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/__init__.py +++ /dev/null @@ -1,74 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .services.lookup_service import LookupServiceClient -from .services.lookup_service import LookupServiceAsyncClient -from .services.registration_service import RegistrationServiceClient -from .services.registration_service import RegistrationServiceAsyncClient - -from .types.endpoint import Endpoint -from .types.lookup_service import ResolveServiceRequest -from .types.lookup_service import ResolveServiceResponse -from .types.namespace import Namespace -from .types.registration_service import CreateEndpointRequest -from .types.registration_service import CreateNamespaceRequest -from .types.registration_service import CreateServiceRequest -from .types.registration_service import DeleteEndpointRequest -from .types.registration_service import DeleteNamespaceRequest -from .types.registration_service import DeleteServiceRequest -from .types.registration_service import GetEndpointRequest -from .types.registration_service import GetNamespaceRequest -from .types.registration_service import GetServiceRequest -from .types.registration_service import ListEndpointsRequest -from .types.registration_service import ListEndpointsResponse -from .types.registration_service import ListNamespacesRequest -from .types.registration_service import ListNamespacesResponse -from .types.registration_service import ListServicesRequest -from .types.registration_service import ListServicesResponse -from .types.registration_service import UpdateEndpointRequest -from .types.registration_service import UpdateNamespaceRequest -from .types.registration_service import UpdateServiceRequest -from .types.service import Service - -__all__ = ( - 'LookupServiceAsyncClient', - 'RegistrationServiceAsyncClient', -'CreateEndpointRequest', -'CreateNamespaceRequest', -'CreateServiceRequest', -'DeleteEndpointRequest', -'DeleteNamespaceRequest', -'DeleteServiceRequest', -'Endpoint', -'GetEndpointRequest', -'GetNamespaceRequest', -'GetServiceRequest', -'ListEndpointsRequest', -'ListEndpointsResponse', -'ListNamespacesRequest', -'ListNamespacesResponse', -'ListServicesRequest', -'ListServicesResponse', -'LookupServiceClient', -'Namespace', -'RegistrationServiceClient', -'ResolveServiceRequest', -'ResolveServiceResponse', -'Service', -'UpdateEndpointRequest', -'UpdateNamespaceRequest', -'UpdateServiceRequest', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/gapic_metadata.json deleted file mode 100644 index be064678..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,227 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.servicedirectory_v1beta1", - "protoPackage": "google.cloud.servicedirectory.v1beta1", - "schema": "1.0", - "services": { - "LookupService": { - "clients": { - "grpc": { - "libraryClient": "LookupServiceClient", - "rpcs": { - "ResolveService": { - "methods": [ - "resolve_service" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LookupServiceAsyncClient", - "rpcs": { - "ResolveService": { - "methods": [ - "resolve_service" - ] - } - } - } - } - }, - "RegistrationService": { - "clients": { - "grpc": { - "libraryClient": "RegistrationServiceClient", - "rpcs": { - "CreateEndpoint": { - "methods": [ - "create_endpoint" - ] - }, - "CreateNamespace": { - "methods": [ - "create_namespace" - ] - }, - "CreateService": { - "methods": [ - "create_service" - ] - }, - "DeleteEndpoint": { - "methods": [ - "delete_endpoint" - ] - }, - "DeleteNamespace": { - "methods": [ - "delete_namespace" - ] - }, - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GetEndpoint": { - "methods": [ - "get_endpoint" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNamespace": { - "methods": [ - "get_namespace" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "ListEndpoints": { - "methods": [ - "list_endpoints" - ] - }, - "ListNamespaces": { - "methods": [ - "list_namespaces" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateEndpoint": { - "methods": [ - "update_endpoint" - ] - }, - "UpdateNamespace": { - "methods": [ - "update_namespace" - ] - }, - "UpdateService": { - "methods": [ - "update_service" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RegistrationServiceAsyncClient", - "rpcs": { - "CreateEndpoint": { - "methods": [ - "create_endpoint" - ] - }, - "CreateNamespace": { - "methods": [ - "create_namespace" - ] - }, - "CreateService": { - "methods": [ - "create_service" - ] - }, - "DeleteEndpoint": { - "methods": [ - "delete_endpoint" - ] - }, - "DeleteNamespace": { - "methods": [ - "delete_namespace" - ] - }, - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GetEndpoint": { - "methods": [ - "get_endpoint" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNamespace": { - "methods": [ - "get_namespace" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "ListEndpoints": { - "methods": [ - "list_endpoints" - ] - }, - "ListNamespaces": { - "methods": [ - "list_namespaces" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateEndpoint": { - "methods": [ - "update_endpoint" - ] - }, - "UpdateNamespace": { - "methods": [ - "update_namespace" - ] - }, - "UpdateService": { - "methods": [ - "update_service" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/py.typed deleted file mode 100644 index 8a62d150..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-service-directory package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/__init__.py +++ /dev/null @@ -1,15 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py deleted file mode 100644 index 926753ac..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 LookupServiceClient -from .async_client import LookupServiceAsyncClient - -__all__ = ( - 'LookupServiceClient', - 'LookupServiceAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py deleted file mode 100644 index 016b82b2..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py +++ /dev/null @@ -1,229 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicedirectory_v1beta1.types import lookup_service -from google.cloud.servicedirectory_v1beta1.types import service -from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport -from .client import LookupServiceClient - - -class LookupServiceAsyncClient: - """Service Directory API for looking up service data at runtime.""" - - _client: LookupServiceClient - - DEFAULT_ENDPOINT = LookupServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LookupServiceClient.DEFAULT_MTLS_ENDPOINT - - endpoint_path = staticmethod(LookupServiceClient.endpoint_path) - parse_endpoint_path = staticmethod(LookupServiceClient.parse_endpoint_path) - network_path = staticmethod(LookupServiceClient.network_path) - parse_network_path = staticmethod(LookupServiceClient.parse_network_path) - service_path = staticmethod(LookupServiceClient.service_path) - parse_service_path = staticmethod(LookupServiceClient.parse_service_path) - common_billing_account_path = staticmethod(LookupServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LookupServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(LookupServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(LookupServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(LookupServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(LookupServiceClient.parse_common_organization_path) - common_project_path = staticmethod(LookupServiceClient.common_project_path) - parse_common_project_path = staticmethod(LookupServiceClient.parse_common_project_path) - common_location_path = staticmethod(LookupServiceClient.common_location_path) - parse_common_location_path = staticmethod(LookupServiceClient.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: - LookupServiceAsyncClient: The constructed client. - """ - return LookupServiceClient.from_service_account_info.__func__(LookupServiceAsyncClient, 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: - LookupServiceAsyncClient: The constructed client. - """ - return LookupServiceClient.from_service_account_file.__func__(LookupServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> LookupServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LookupServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(LookupServiceClient).get_transport_class, type(LookupServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, LookupServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the lookup 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 (Union[str, ~.LookupServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = LookupServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def resolve_service(self, - request: lookup_service.ResolveServiceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> lookup_service.ResolveServiceResponse: - r"""Returns a - [service][google.cloud.servicedirectory.v1beta1.Service] and its - associated endpoints. Resolving a service is not considered an - active developer method. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.ResolveServiceRequest`): - The request object. The request message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. - Looks up a service by its name, returns the service and - its endpoints. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.servicedirectory_v1beta1.types.ResolveServiceResponse: - The response message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. - - """ - # Create or coerce a protobuf request object. - request = lookup_service.ResolveServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.resolve_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-service-directory", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "LookupServiceAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py deleted file mode 100644 index cdd3bdcf..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py +++ /dev/null @@ -1,445 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -from google.cloud.servicedirectory_v1beta1.types import lookup_service -from google.cloud.servicedirectory_v1beta1.types import service -from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import LookupServiceGrpcTransport -from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport - - -class LookupServiceClientMeta(type): - """Metaclass for the LookupService 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[LookupServiceTransport]] - _transport_registry["grpc"] = LookupServiceGrpcTransport - _transport_registry["grpc_asyncio"] = LookupServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[LookupServiceTransport]: - """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 LookupServiceClient(metaclass=LookupServiceClientMeta): - """Service Directory API for looking up service data at runtime.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "servicedirectory.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LookupServiceClient: 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: - LookupServiceClient: 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) -> LookupServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LookupServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def endpoint_path(project: str,location: str,namespace: str,service: str,endpoint: str,) -> str: - """Returns a fully-qualified endpoint string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) - - @staticmethod - def parse_endpoint_path(path: str) -> Dict[str,str]: - """Parses a endpoint path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def network_path(project: str,network: str,) -> str: - """Returns a fully-qualified network string.""" - return "projects/{project}/locations/global/networks/{network}".format(project=project, network=network, ) - - @staticmethod - def parse_network_path(path: str) -> Dict[str,str]: - """Parses a network path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/global/networks/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_path(project: str,location: str,namespace: str,service: str,) -> str: - """Returns a fully-qualified service string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - - @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: - """Parses a service path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, LookupServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the lookup 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 (Union[str, LookupServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, LookupServiceTransport): - # transport is a LookupServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def resolve_service(self, - request: Union[lookup_service.ResolveServiceRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> lookup_service.ResolveServiceResponse: - r"""Returns a - [service][google.cloud.servicedirectory.v1beta1.Service] and its - associated endpoints. Resolving a service is not considered an - active developer method. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.ResolveServiceRequest, dict]): - The request object. The request message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. - Looks up a service by its name, returns the service and - its endpoints. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.servicedirectory_v1beta1.types.ResolveServiceResponse: - The response message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a lookup_service.ResolveServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, lookup_service.ResolveServiceRequest): - request = lookup_service.ResolveServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.resolve_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-service-directory", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "LookupServiceClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py deleted file mode 100644 index 437f5631..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 LookupServiceTransport -from .grpc import LookupServiceGrpcTransport -from .grpc_asyncio import LookupServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LookupServiceTransport]] -_transport_registry['grpc'] = LookupServiceGrpcTransport -_transport_registry['grpc_asyncio'] = LookupServiceGrpcAsyncIOTransport - -__all__ = ( - 'LookupServiceTransport', - 'LookupServiceGrpcTransport', - 'LookupServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py deleted file mode 100644 index 03732d5a..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py +++ /dev/null @@ -1,177 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicedirectory_v1beta1.types import lookup_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-service-directory', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class LookupServiceTransport(abc.ABC): - """Abstract transport class for LookupService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'servicedirectory.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.resolve_service: gapic_v1.method.wrap_method( - self.resolve_service, - 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 resolve_service(self) -> Callable[ - [lookup_service.ResolveServiceRequest], - Union[ - lookup_service.ResolveServiceResponse, - Awaitable[lookup_service.ResolveServiceResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'LookupServiceTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py deleted file mode 100644 index 617e04f7..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py +++ /dev/null @@ -1,257 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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.servicedirectory_v1beta1.types import lookup_service -from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO - - -class LookupServiceGrpcTransport(LookupServiceTransport): - """gRPC backend transport for LookupService. - - Service Directory API for looking up service data at runtime. - - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 resolve_service(self) -> Callable[ - [lookup_service.ResolveServiceRequest], - lookup_service.ResolveServiceResponse]: - r"""Return a callable for the resolve service method over gRPC. - - Returns a - [service][google.cloud.servicedirectory.v1beta1.Service] and its - associated endpoints. Resolving a service is not considered an - active developer method. - - Returns: - Callable[[~.ResolveServiceRequest], - ~.ResolveServiceResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'resolve_service' not in self._stubs: - self._stubs['resolve_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.LookupService/ResolveService', - request_serializer=lookup_service.ResolveServiceRequest.serialize, - response_deserializer=lookup_service.ResolveServiceResponse.deserialize, - ) - return self._stubs['resolve_service'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'LookupServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py deleted file mode 100644 index 96892495..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,262 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.servicedirectory_v1beta1.types import lookup_service -from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import LookupServiceGrpcTransport - - -class LookupServiceGrpcAsyncIOTransport(LookupServiceTransport): - """gRPC AsyncIO backend transport for LookupService. - - Service Directory API for looking up service data at runtime. - - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def resolve_service(self) -> Callable[ - [lookup_service.ResolveServiceRequest], - Awaitable[lookup_service.ResolveServiceResponse]]: - r"""Return a callable for the resolve service method over gRPC. - - Returns a - [service][google.cloud.servicedirectory.v1beta1.Service] and its - associated endpoints. Resolving a service is not considered an - active developer method. - - Returns: - Callable[[~.ResolveServiceRequest], - Awaitable[~.ResolveServiceResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'resolve_service' not in self._stubs: - self._stubs['resolve_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.LookupService/ResolveService', - request_serializer=lookup_service.ResolveServiceRequest.serialize, - response_deserializer=lookup_service.ResolveServiceResponse.deserialize, - ) - return self._stubs['resolve_service'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'LookupServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py deleted file mode 100644 index 5097508c..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 RegistrationServiceClient -from .async_client import RegistrationServiceAsyncClient - -__all__ = ( - 'RegistrationServiceClient', - 'RegistrationServiceAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py deleted file mode 100644 index 967760cd..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py +++ /dev/null @@ -1,1740 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicedirectory_v1beta1.services.registration_service import pagers -from google.cloud.servicedirectory_v1beta1.types import endpoint -from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1beta1.types import namespace -from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1beta1.types import registration_service -from google.cloud.servicedirectory_v1beta1.types import service -from google.cloud.servicedirectory_v1beta1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport -from .client import RegistrationServiceClient - - -class RegistrationServiceAsyncClient: - """Service Directory API for registering services. It defines the - following resource model: - - - The API has a collection of - [Namespace][google.cloud.servicedirectory.v1beta1.Namespace] - resources, named ``projects/*/locations/*/namespaces/*``. - - - Each Namespace has a collection of - [Service][google.cloud.servicedirectory.v1beta1.Service] - resources, named - ``projects/*/locations/*/namespaces/*/services/*``. - - - Each Service has a collection of - [Endpoint][google.cloud.servicedirectory.v1beta1.Endpoint] - resources, named - ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. - """ - - _client: RegistrationServiceClient - - DEFAULT_ENDPOINT = RegistrationServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RegistrationServiceClient.DEFAULT_MTLS_ENDPOINT - - endpoint_path = staticmethod(RegistrationServiceClient.endpoint_path) - parse_endpoint_path = staticmethod(RegistrationServiceClient.parse_endpoint_path) - namespace_path = staticmethod(RegistrationServiceClient.namespace_path) - parse_namespace_path = staticmethod(RegistrationServiceClient.parse_namespace_path) - network_path = staticmethod(RegistrationServiceClient.network_path) - parse_network_path = staticmethod(RegistrationServiceClient.parse_network_path) - service_path = staticmethod(RegistrationServiceClient.service_path) - parse_service_path = staticmethod(RegistrationServiceClient.parse_service_path) - common_billing_account_path = staticmethod(RegistrationServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RegistrationServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RegistrationServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(RegistrationServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(RegistrationServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(RegistrationServiceClient.parse_common_organization_path) - common_project_path = staticmethod(RegistrationServiceClient.common_project_path) - parse_common_project_path = staticmethod(RegistrationServiceClient.parse_common_project_path) - common_location_path = staticmethod(RegistrationServiceClient.common_location_path) - parse_common_location_path = staticmethod(RegistrationServiceClient.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: - RegistrationServiceAsyncClient: The constructed client. - """ - return RegistrationServiceClient.from_service_account_info.__func__(RegistrationServiceAsyncClient, 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: - RegistrationServiceAsyncClient: The constructed client. - """ - return RegistrationServiceClient.from_service_account_file.__func__(RegistrationServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> RegistrationServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RegistrationServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RegistrationServiceClient).get_transport_class, type(RegistrationServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, RegistrationServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the registration 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 (Union[str, ~.RegistrationServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RegistrationServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_namespace(self, - request: registration_service.CreateNamespaceRequest = None, - *, - parent: str = None, - namespace: gcs_namespace.Namespace = None, - namespace_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_namespace.Namespace: - r"""Creates a namespace, and returns the new namespace. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.CreateNamespaceRequest`): - The request object. The request message for - [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateNamespace]. - parent (:class:`str`): - Required. The resource name of the - project and location the namespace will - be created in. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - namespace (:class:`google.cloud.servicedirectory_v1beta1.types.Namespace`): - Required. A namespace with initial - fields set. - - This corresponds to the ``namespace`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - namespace_id (:class:`str`): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``namespace_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1beta1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, namespace, namespace_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.CreateNamespaceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if namespace is not None: - request.namespace = namespace - if namespace_id is not None: - request.namespace_id = namespace_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_namespace, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_namespaces(self, - request: registration_service.ListNamespacesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNamespacesAsyncPager: - r"""Lists all namespaces. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.ListNamespacesRequest`): - The request object. The request message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. - parent (:class:`str`): - Required. The resource name of the - project and location whose namespaces - you'd like to list. - - 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.servicedirectory_v1beta1.services.registration_service.pagers.ListNamespacesAsyncPager: - The response message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.ListNamespacesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_namespaces, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListNamespacesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_namespace(self, - request: registration_service.GetNamespaceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> namespace.Namespace: - r"""Gets a namespace. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.GetNamespaceRequest`): - The request object. The request message for - [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.GetNamespace]. - name (:class:`str`): - Required. The name of the namespace - to retrieve. - - 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.servicedirectory_v1beta1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1beta1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.GetNamespaceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_namespace, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_namespace(self, - request: registration_service.UpdateNamespaceRequest = None, - *, - namespace: gcs_namespace.Namespace = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_namespace.Namespace: - r"""Updates a namespace. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.UpdateNamespaceRequest`): - The request object. The request message for - [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateNamespace]. - namespace (:class:`google.cloud.servicedirectory_v1beta1.types.Namespace`): - Required. The updated namespace. - This corresponds to the ``namespace`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1beta1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([namespace, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.UpdateNamespaceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if namespace is not None: - request.namespace = namespace - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_namespace, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("namespace.name", request.namespace.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_namespace(self, - request: registration_service.DeleteNamespaceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a namespace. This also deletes all services - and endpoints in the namespace. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.DeleteNamespaceRequest`): - The request object. The request message for - [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteNamespace]. - name (:class:`str`): - Required. The name of the namespace - to delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.DeleteNamespaceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_namespace, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def create_service(self, - request: registration_service.CreateServiceRequest = None, - *, - parent: str = None, - service: gcs_service.Service = None, - service_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_service.Service: - r"""Creates a service, and returns the new service. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.CreateServiceRequest`): - The request object. The request message for - [RegistrationService.CreateService][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateService]. - parent (:class:`str`): - Required. The resource name of the - namespace this service will belong to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service (:class:`google.cloud.servicedirectory_v1beta1.types.Service`): - Required. A service with initial - fields set. - - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_id (:class:`str`): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``service_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, service, service_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.CreateServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if service is not None: - request.service = service - if service_id is not None: - request.service_id = service_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_services(self, - request: registration_service.ListServicesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServicesAsyncPager: - r"""Lists all services belonging to a namespace. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.ListServicesRequest`): - The request object. The request message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. - parent (:class:`str`): - Required. The resource name of the - namespace whose services you'd like to - list. - - 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.servicedirectory_v1beta1.services.registration_service.pagers.ListServicesAsyncPager: - The response message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.ListServicesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_services, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServicesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_service(self, - request: registration_service.GetServiceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.Service: - r"""Gets a service. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.GetServiceRequest`): - The request object. The request message for - [RegistrationService.GetService][google.cloud.servicedirectory.v1beta1.RegistrationService.GetService]. - This should not be used for looking up a service. - Insead, use the `resolve` method as it contains all - endpoints and associated metadata. - name (:class:`str`): - Required. The name of the service to - get. - - 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.servicedirectory_v1beta1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.GetServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_service(self, - request: registration_service.UpdateServiceRequest = None, - *, - service: gcs_service.Service = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_service.Service: - r"""Updates a service. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.UpdateServiceRequest`): - The request object. The request message for - [RegistrationService.UpdateService][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateService]. - service (:class:`google.cloud.servicedirectory_v1beta1.types.Service`): - Required. The updated service. - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.UpdateServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service is not None: - request.service = service - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service.name", request.service.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_service(self, - request: registration_service.DeleteServiceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a service. This also deletes all endpoints - associated with the service. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.DeleteServiceRequest`): - The request object. The request message for - [RegistrationService.DeleteService][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteService]. - name (:class:`str`): - Required. The name of the service to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.DeleteServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def create_endpoint(self, - request: registration_service.CreateEndpointRequest = None, - *, - parent: str = None, - endpoint: gcs_endpoint.Endpoint = None, - endpoint_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_endpoint.Endpoint: - r"""Creates an endpoint, and returns the new endpoint. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.CreateEndpointRequest`): - The request object. The request message for - [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateEndpoint]. - parent (:class:`str`): - Required. The resource name of the - service that this endpoint provides. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint (:class:`google.cloud.servicedirectory_v1beta1.types.Endpoint`): - Required. A endpoint with initial - fields set. - - This corresponds to the ``endpoint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint_id (:class:`str`): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``endpoint_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1beta1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, endpoint, endpoint_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.CreateEndpointRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if endpoint is not None: - request.endpoint = endpoint - if endpoint_id is not None: - request.endpoint_id = endpoint_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_endpoint, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_endpoints(self, - request: registration_service.ListEndpointsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEndpointsAsyncPager: - r"""Lists all endpoints. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.ListEndpointsRequest`): - The request object. The request message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. - parent (:class:`str`): - Required. The resource name of the - service whose endpoints you'd like to - list. - - 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.servicedirectory_v1beta1.services.registration_service.pagers.ListEndpointsAsyncPager: - The response message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.ListEndpointsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_endpoints, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListEndpointsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_endpoint(self, - request: registration_service.GetEndpointRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> endpoint.Endpoint: - r"""Gets an endpoint. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.GetEndpointRequest`): - The request object. The request message for - [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.GetEndpoint]. - This should not be used to lookup endpoints at runtime. - Instead, use the `resolve` method. - name (:class:`str`): - Required. The name of the endpoint to - get. - - 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.servicedirectory_v1beta1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1beta1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.GetEndpointRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_endpoint, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_endpoint(self, - request: registration_service.UpdateEndpointRequest = None, - *, - endpoint: gcs_endpoint.Endpoint = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_endpoint.Endpoint: - r"""Updates an endpoint. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.UpdateEndpointRequest`): - The request object. The request message for - [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateEndpoint]. - endpoint (:class:`google.cloud.servicedirectory_v1beta1.types.Endpoint`): - Required. The updated endpoint. - This corresponds to the ``endpoint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1beta1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([endpoint, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.UpdateEndpointRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if endpoint is not None: - request.endpoint = endpoint - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_endpoint, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("endpoint.name", request.endpoint.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_endpoint(self, - request: registration_service.DeleteEndpointRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an endpoint. - - Args: - request (:class:`google.cloud.servicedirectory_v1beta1.types.DeleteEndpointRequest`): - The request object. The request message for - [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteEndpoint]. - name (:class:`str`): - Required. The name of the endpoint to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registration_service.DeleteEndpointRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_endpoint, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_iam_policy(self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM Policy for a resource (namespace or - service only). - - Args: - request (:class:`google.iam.v1.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: - google.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy(self, - request: iam_policy_pb2.SetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM Policy for a resource (namespace or - service only). - - Args: - request (:class:`google.iam.v1.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: - google.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def test_iam_permissions(self, - request: iam_policy_pb2.TestIamPermissionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests IAM permissions for a resource (namespace or - service only). - - Args: - request (:class:`google.iam.v1.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: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-service-directory", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "RegistrationServiceAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py deleted file mode 100644 index 532efd4d..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py +++ /dev/null @@ -1,1961 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -from google.cloud.servicedirectory_v1beta1.services.registration_service import pagers -from google.cloud.servicedirectory_v1beta1.types import endpoint -from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1beta1.types import namespace -from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1beta1.types import registration_service -from google.cloud.servicedirectory_v1beta1.types import service -from google.cloud.servicedirectory_v1beta1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RegistrationServiceGrpcTransport -from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport - - -class RegistrationServiceClientMeta(type): - """Metaclass for the RegistrationService 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[RegistrationServiceTransport]] - _transport_registry["grpc"] = RegistrationServiceGrpcTransport - _transport_registry["grpc_asyncio"] = RegistrationServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[RegistrationServiceTransport]: - """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 RegistrationServiceClient(metaclass=RegistrationServiceClientMeta): - """Service Directory API for registering services. It defines the - following resource model: - - - The API has a collection of - [Namespace][google.cloud.servicedirectory.v1beta1.Namespace] - resources, named ``projects/*/locations/*/namespaces/*``. - - - Each Namespace has a collection of - [Service][google.cloud.servicedirectory.v1beta1.Service] - resources, named - ``projects/*/locations/*/namespaces/*/services/*``. - - - Each Service has a collection of - [Endpoint][google.cloud.servicedirectory.v1beta1.Endpoint] - resources, named - ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "servicedirectory.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegistrationServiceClient: 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: - RegistrationServiceClient: 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) -> RegistrationServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RegistrationServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def endpoint_path(project: str,location: str,namespace: str,service: str,endpoint: str,) -> str: - """Returns a fully-qualified endpoint string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) - - @staticmethod - def parse_endpoint_path(path: str) -> Dict[str,str]: - """Parses a endpoint path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def namespace_path(project: str,location: str,namespace: str,) -> str: - """Returns a fully-qualified namespace string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}".format(project=project, location=location, namespace=namespace, ) - - @staticmethod - def parse_namespace_path(path: str) -> Dict[str,str]: - """Parses a namespace path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def network_path(project: str,network: str,) -> str: - """Returns a fully-qualified network string.""" - return "projects/{project}/locations/global/networks/{network}".format(project=project, network=network, ) - - @staticmethod - def parse_network_path(path: str) -> Dict[str,str]: - """Parses a network path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/global/networks/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_path(project: str,location: str,namespace: str,service: str,) -> str: - """Returns a fully-qualified service string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - - @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: - """Parses a service path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RegistrationServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the registration 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 (Union[str, RegistrationServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RegistrationServiceTransport): - # transport is a RegistrationServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_namespace(self, - request: Union[registration_service.CreateNamespaceRequest, dict] = None, - *, - parent: str = None, - namespace: gcs_namespace.Namespace = None, - namespace_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_namespace.Namespace: - r"""Creates a namespace, and returns the new namespace. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.CreateNamespaceRequest, dict]): - The request object. The request message for - [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateNamespace]. - parent (str): - Required. The resource name of the - project and location the namespace will - be created in. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - namespace (google.cloud.servicedirectory_v1beta1.types.Namespace): - Required. A namespace with initial - fields set. - - This corresponds to the ``namespace`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - namespace_id (str): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``namespace_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1beta1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, namespace, namespace_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.CreateNamespaceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.CreateNamespaceRequest): - request = registration_service.CreateNamespaceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if namespace is not None: - request.namespace = namespace - if namespace_id is not None: - request.namespace_id = namespace_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_namespace] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_namespaces(self, - request: Union[registration_service.ListNamespacesRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNamespacesPager: - r"""Lists all namespaces. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.ListNamespacesRequest, dict]): - The request object. The request message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. - parent (str): - Required. The resource name of the - project and location whose namespaces - you'd like to list. - - 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.servicedirectory_v1beta1.services.registration_service.pagers.ListNamespacesPager: - The response message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.ListNamespacesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.ListNamespacesRequest): - request = registration_service.ListNamespacesRequest(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_namespaces] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListNamespacesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_namespace(self, - request: Union[registration_service.GetNamespaceRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> namespace.Namespace: - r"""Gets a namespace. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.GetNamespaceRequest, dict]): - The request object. The request message for - [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.GetNamespace]. - name (str): - Required. The name of the namespace - to retrieve. - - 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.servicedirectory_v1beta1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1beta1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.GetNamespaceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.GetNamespaceRequest): - request = registration_service.GetNamespaceRequest(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_namespace] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_namespace(self, - request: Union[registration_service.UpdateNamespaceRequest, dict] = None, - *, - namespace: gcs_namespace.Namespace = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_namespace.Namespace: - r"""Updates a namespace. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.UpdateNamespaceRequest, dict]): - The request object. The request message for - [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateNamespace]. - namespace (google.cloud.servicedirectory_v1beta1.types.Namespace): - Required. The updated namespace. - This corresponds to the ``namespace`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Namespace: - A container for [services][google.cloud.servicedirectory.v1beta1.Service]. - Namespaces allow administrators to group services - together and define permissions for a collection of - services. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([namespace, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.UpdateNamespaceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.UpdateNamespaceRequest): - request = registration_service.UpdateNamespaceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if namespace is not None: - request.namespace = namespace - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_namespace] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("namespace.name", request.namespace.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_namespace(self, - request: Union[registration_service.DeleteNamespaceRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a namespace. This also deletes all services - and endpoints in the namespace. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.DeleteNamespaceRequest, dict]): - The request object. The request message for - [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteNamespace]. - name (str): - Required. The name of the namespace - to delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.DeleteNamespaceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.DeleteNamespaceRequest): - request = registration_service.DeleteNamespaceRequest(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_namespace] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def create_service(self, - request: Union[registration_service.CreateServiceRequest, dict] = None, - *, - parent: str = None, - service: gcs_service.Service = None, - service_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_service.Service: - r"""Creates a service, and returns the new service. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.CreateServiceRequest, dict]): - The request object. The request message for - [RegistrationService.CreateService][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateService]. - parent (str): - Required. The resource name of the - namespace this service will belong to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service (google.cloud.servicedirectory_v1beta1.types.Service): - Required. A service with initial - fields set. - - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_id (str): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``service_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, service, service_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.CreateServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.CreateServiceRequest): - request = registration_service.CreateServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if service is not None: - request.service = service - if service_id is not None: - request.service_id = service_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_services(self, - request: Union[registration_service.ListServicesRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServicesPager: - r"""Lists all services belonging to a namespace. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.ListServicesRequest, dict]): - The request object. The request message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. - parent (str): - Required. The resource name of the - namespace whose services you'd like to - list. - - 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.servicedirectory_v1beta1.services.registration_service.pagers.ListServicesPager: - The response message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.ListServicesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.ListServicesRequest): - request = registration_service.ListServicesRequest(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_services] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServicesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_service(self, - request: Union[registration_service.GetServiceRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.Service: - r"""Gets a service. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.GetServiceRequest, dict]): - The request object. The request message for - [RegistrationService.GetService][google.cloud.servicedirectory.v1beta1.RegistrationService.GetService]. - This should not be used for looking up a service. - Insead, use the `resolve` method as it contains all - endpoints and associated metadata. - name (str): - Required. The name of the service to - get. - - 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.servicedirectory_v1beta1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.GetServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.GetServiceRequest): - request = registration_service.GetServiceRequest(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_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_service(self, - request: Union[registration_service.UpdateServiceRequest, dict] = None, - *, - service: gcs_service.Service = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_service.Service: - r"""Updates a service. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.UpdateServiceRequest, dict]): - The request object. The request message for - [RegistrationService.UpdateService][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateService]. - service (google.cloud.servicedirectory_v1beta1.types.Service): - Required. The updated service. - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Service: - An individual service. A service contains a name and optional metadata. - A service must exist before - [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] - can be added to it. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.UpdateServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.UpdateServiceRequest): - request = registration_service.UpdateServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service is not None: - request.service = service - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service.name", request.service.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_service(self, - request: Union[registration_service.DeleteServiceRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a service. This also deletes all endpoints - associated with the service. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.DeleteServiceRequest, dict]): - The request object. The request message for - [RegistrationService.DeleteService][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteService]. - name (str): - Required. The name of the service to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.DeleteServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.DeleteServiceRequest): - request = registration_service.DeleteServiceRequest(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_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def create_endpoint(self, - request: Union[registration_service.CreateEndpointRequest, dict] = None, - *, - parent: str = None, - endpoint: gcs_endpoint.Endpoint = None, - endpoint_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_endpoint.Endpoint: - r"""Creates an endpoint, and returns the new endpoint. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.CreateEndpointRequest, dict]): - The request object. The request message for - [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateEndpoint]. - parent (str): - Required. The resource name of the - service that this endpoint provides. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint (google.cloud.servicedirectory_v1beta1.types.Endpoint): - Required. A endpoint with initial - fields set. - - This corresponds to the ``endpoint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint_id (str): - Required. The Resource ID must be 1-63 characters long, - and comply with RFC1035. Specifically, the name must be - 1-63 characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the - first character must be a lowercase letter, and all - following characters must be a dash, lowercase letter, - or digit, except the last character, which cannot be a - dash. - - This corresponds to the ``endpoint_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1beta1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, endpoint, endpoint_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.CreateEndpointRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.CreateEndpointRequest): - request = registration_service.CreateEndpointRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if endpoint is not None: - request.endpoint = endpoint - if endpoint_id is not None: - request.endpoint_id = endpoint_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_endpoint] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_endpoints(self, - request: Union[registration_service.ListEndpointsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEndpointsPager: - r"""Lists all endpoints. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.ListEndpointsRequest, dict]): - The request object. The request message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. - parent (str): - Required. The resource name of the - service whose endpoints you'd like to - list. - - 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.servicedirectory_v1beta1.services.registration_service.pagers.ListEndpointsPager: - The response message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.ListEndpointsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.ListEndpointsRequest): - request = registration_service.ListEndpointsRequest(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_endpoints] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListEndpointsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_endpoint(self, - request: Union[registration_service.GetEndpointRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> endpoint.Endpoint: - r"""Gets an endpoint. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.GetEndpointRequest, dict]): - The request object. The request message for - [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.GetEndpoint]. - This should not be used to lookup endpoints at runtime. - Instead, use the `resolve` method. - name (str): - Required. The name of the endpoint to - get. - - 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.servicedirectory_v1beta1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1beta1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.GetEndpointRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.GetEndpointRequest): - request = registration_service.GetEndpointRequest(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_endpoint] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_endpoint(self, - request: Union[registration_service.UpdateEndpointRequest, dict] = None, - *, - endpoint: gcs_endpoint.Endpoint = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_endpoint.Endpoint: - r"""Updates an endpoint. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.UpdateEndpointRequest, dict]): - The request object. The request message for - [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateEndpoint]. - endpoint (google.cloud.servicedirectory_v1beta1.types.Endpoint): - Required. The updated endpoint. - This corresponds to the ``endpoint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.servicedirectory_v1beta1.types.Endpoint: - An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1beta1.Service]. - The service must already exist to create an endpoint. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([endpoint, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.UpdateEndpointRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.UpdateEndpointRequest): - request = registration_service.UpdateEndpointRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if endpoint is not None: - request.endpoint = endpoint - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_endpoint] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("endpoint.name", request.endpoint.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_endpoint(self, - request: Union[registration_service.DeleteEndpointRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an endpoint. - - Args: - request (Union[google.cloud.servicedirectory_v1beta1.types.DeleteEndpointRequest, dict]): - The request object. The request message for - [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteEndpoint]. - name (str): - Required. The name of the endpoint to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registration_service.DeleteEndpointRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registration_service.DeleteEndpointRequest): - request = registration_service.DeleteEndpointRequest(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_endpoint] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM Policy for a resource (namespace or - service only). - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - 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: - google.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy(self, - request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM Policy for a resource (namespace or - service only). - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - 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: - google.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def test_iam_permissions(self, - request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests IAM permissions for a resource (namespace or - service only). - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - 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: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-service-directory", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "RegistrationServiceClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py deleted file mode 100644 index 13ccc6ca..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py +++ /dev/null @@ -1,387 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.servicedirectory_v1beta1.types import endpoint -from google.cloud.servicedirectory_v1beta1.types import namespace -from google.cloud.servicedirectory_v1beta1.types import registration_service -from google.cloud.servicedirectory_v1beta1.types import service - - -class ListNamespacesPager: - """A pager for iterating through ``list_namespaces`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``namespaces`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNamespaces`` requests and continue to iterate - through the ``namespaces`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse` - 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[..., registration_service.ListNamespacesResponse], - request: registration_service.ListNamespacesRequest, - response: registration_service.ListNamespacesResponse, - *, - 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.servicedirectory_v1beta1.types.ListNamespacesRequest): - The initial request object. - response (google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListNamespacesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registration_service.ListNamespacesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[namespace.Namespace]: - for page in self.pages: - yield from page.namespaces - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNamespacesAsyncPager: - """A pager for iterating through ``list_namespaces`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``namespaces`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNamespaces`` requests and continue to iterate - through the ``namespaces`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse` - 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[registration_service.ListNamespacesResponse]], - request: registration_service.ListNamespacesRequest, - response: registration_service.ListNamespacesResponse, - *, - 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.servicedirectory_v1beta1.types.ListNamespacesRequest): - The initial request object. - response (google.cloud.servicedirectory_v1beta1.types.ListNamespacesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListNamespacesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registration_service.ListNamespacesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[namespace.Namespace]: - async def async_generator(): - async for page in self.pages: - for response in page.namespaces: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServicesPager: - """A pager for iterating through ``list_services`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1beta1.types.ListServicesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``services`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServices`` requests and continue to iterate - through the ``services`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListServicesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., registration_service.ListServicesResponse], - request: registration_service.ListServicesRequest, - response: registration_service.ListServicesResponse, - *, - 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.servicedirectory_v1beta1.types.ListServicesRequest): - The initial request object. - response (google.cloud.servicedirectory_v1beta1.types.ListServicesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListServicesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registration_service.ListServicesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[service.Service]: - for page in self.pages: - yield from page.services - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServicesAsyncPager: - """A pager for iterating through ``list_services`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1beta1.types.ListServicesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``services`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServices`` requests and continue to iterate - through the ``services`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListServicesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[registration_service.ListServicesResponse]], - request: registration_service.ListServicesRequest, - response: registration_service.ListServicesResponse, - *, - 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.servicedirectory_v1beta1.types.ListServicesRequest): - The initial request object. - response (google.cloud.servicedirectory_v1beta1.types.ListServicesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListServicesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registration_service.ListServicesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[service.Service]: - async def async_generator(): - async for page in self.pages: - for response in page.services: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEndpointsPager: - """A pager for iterating through ``list_endpoints`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``endpoints`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEndpoints`` requests and continue to iterate - through the ``endpoints`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse` - 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[..., registration_service.ListEndpointsResponse], - request: registration_service.ListEndpointsRequest, - response: registration_service.ListEndpointsResponse, - *, - 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.servicedirectory_v1beta1.types.ListEndpointsRequest): - The initial request object. - response (google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListEndpointsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registration_service.ListEndpointsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[endpoint.Endpoint]: - for page in self.pages: - yield from page.endpoints - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEndpointsAsyncPager: - """A pager for iterating through ``list_endpoints`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``endpoints`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEndpoints`` requests and continue to iterate - through the ``endpoints`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse` - 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[registration_service.ListEndpointsResponse]], - request: registration_service.ListEndpointsRequest, - response: registration_service.ListEndpointsResponse, - *, - 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.servicedirectory_v1beta1.types.ListEndpointsRequest): - The initial request object. - response (google.cloud.servicedirectory_v1beta1.types.ListEndpointsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = registration_service.ListEndpointsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registration_service.ListEndpointsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[endpoint.Endpoint]: - async def async_generator(): - async for page in self.pages: - for response in page.endpoints: - 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/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py deleted file mode 100644 index a584bf16..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 RegistrationServiceTransport -from .grpc import RegistrationServiceGrpcTransport -from .grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RegistrationServiceTransport]] -_transport_registry['grpc'] = RegistrationServiceGrpcTransport -_transport_registry['grpc_asyncio'] = RegistrationServiceGrpcAsyncIOTransport - -__all__ = ( - 'RegistrationServiceTransport', - 'RegistrationServiceGrpcTransport', - 'RegistrationServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py deleted file mode 100644 index 79d45c98..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py +++ /dev/null @@ -1,424 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicedirectory_v1beta1.types import endpoint -from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1beta1.types import namespace -from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1beta1.types import registration_service -from google.cloud.servicedirectory_v1beta1.types import service -from google.cloud.servicedirectory_v1beta1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-service-directory', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class RegistrationServiceTransport(abc.ABC): - """Abstract transport class for RegistrationService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'servicedirectory.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_namespace: gapic_v1.method.wrap_method( - self.create_namespace, - default_timeout=None, - client_info=client_info, - ), - self.list_namespaces: gapic_v1.method.wrap_method( - self.list_namespaces, - default_timeout=None, - client_info=client_info, - ), - self.get_namespace: gapic_v1.method.wrap_method( - self.get_namespace, - default_timeout=None, - client_info=client_info, - ), - self.update_namespace: gapic_v1.method.wrap_method( - self.update_namespace, - default_timeout=None, - client_info=client_info, - ), - self.delete_namespace: gapic_v1.method.wrap_method( - self.delete_namespace, - default_timeout=None, - client_info=client_info, - ), - self.create_service: gapic_v1.method.wrap_method( - self.create_service, - default_timeout=None, - client_info=client_info, - ), - self.list_services: gapic_v1.method.wrap_method( - self.list_services, - default_timeout=None, - client_info=client_info, - ), - self.get_service: gapic_v1.method.wrap_method( - self.get_service, - default_timeout=None, - client_info=client_info, - ), - self.update_service: gapic_v1.method.wrap_method( - self.update_service, - default_timeout=None, - client_info=client_info, - ), - self.delete_service: gapic_v1.method.wrap_method( - self.delete_service, - default_timeout=None, - client_info=client_info, - ), - self.create_endpoint: gapic_v1.method.wrap_method( - self.create_endpoint, - default_timeout=None, - client_info=client_info, - ), - self.list_endpoints: gapic_v1.method.wrap_method( - self.list_endpoints, - default_timeout=None, - client_info=client_info, - ), - self.get_endpoint: gapic_v1.method.wrap_method( - self.get_endpoint, - default_timeout=None, - client_info=client_info, - ), - self.update_endpoint: gapic_v1.method.wrap_method( - self.update_endpoint, - default_timeout=None, - client_info=client_info, - ), - self.delete_endpoint: gapic_v1.method.wrap_method( - self.delete_endpoint, - 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, - ), - } - - 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 create_namespace(self) -> Callable[ - [registration_service.CreateNamespaceRequest], - Union[ - gcs_namespace.Namespace, - Awaitable[gcs_namespace.Namespace] - ]]: - raise NotImplementedError() - - @property - def list_namespaces(self) -> Callable[ - [registration_service.ListNamespacesRequest], - Union[ - registration_service.ListNamespacesResponse, - Awaitable[registration_service.ListNamespacesResponse] - ]]: - raise NotImplementedError() - - @property - def get_namespace(self) -> Callable[ - [registration_service.GetNamespaceRequest], - Union[ - namespace.Namespace, - Awaitable[namespace.Namespace] - ]]: - raise NotImplementedError() - - @property - def update_namespace(self) -> Callable[ - [registration_service.UpdateNamespaceRequest], - Union[ - gcs_namespace.Namespace, - Awaitable[gcs_namespace.Namespace] - ]]: - raise NotImplementedError() - - @property - def delete_namespace(self) -> Callable[ - [registration_service.DeleteNamespaceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_service(self) -> Callable[ - [registration_service.CreateServiceRequest], - Union[ - gcs_service.Service, - Awaitable[gcs_service.Service] - ]]: - raise NotImplementedError() - - @property - def list_services(self) -> Callable[ - [registration_service.ListServicesRequest], - Union[ - registration_service.ListServicesResponse, - Awaitable[registration_service.ListServicesResponse] - ]]: - raise NotImplementedError() - - @property - def get_service(self) -> Callable[ - [registration_service.GetServiceRequest], - Union[ - service.Service, - Awaitable[service.Service] - ]]: - raise NotImplementedError() - - @property - def update_service(self) -> Callable[ - [registration_service.UpdateServiceRequest], - Union[ - gcs_service.Service, - Awaitable[gcs_service.Service] - ]]: - raise NotImplementedError() - - @property - def delete_service(self) -> Callable[ - [registration_service.DeleteServiceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_endpoint(self) -> Callable[ - [registration_service.CreateEndpointRequest], - Union[ - gcs_endpoint.Endpoint, - Awaitable[gcs_endpoint.Endpoint] - ]]: - raise NotImplementedError() - - @property - def list_endpoints(self) -> Callable[ - [registration_service.ListEndpointsRequest], - Union[ - registration_service.ListEndpointsResponse, - Awaitable[registration_service.ListEndpointsResponse] - ]]: - raise NotImplementedError() - - @property - def get_endpoint(self) -> Callable[ - [registration_service.GetEndpointRequest], - Union[ - endpoint.Endpoint, - Awaitable[endpoint.Endpoint] - ]]: - raise NotImplementedError() - - @property - def update_endpoint(self) -> Callable[ - [registration_service.UpdateEndpointRequest], - Union[ - gcs_endpoint.Endpoint, - Awaitable[gcs_endpoint.Endpoint] - ]]: - raise NotImplementedError() - - @property - def delete_endpoint(self) -> Callable[ - [registration_service.DeleteEndpointRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - 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 set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - 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() - - -__all__ = ( - 'RegistrationServiceTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py deleted file mode 100644 index 0d49c0ae..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py +++ /dev/null @@ -1,725 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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.servicedirectory_v1beta1.types import endpoint -from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1beta1.types import namespace -from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1beta1.types import registration_service -from google.cloud.servicedirectory_v1beta1.types import service -from google.cloud.servicedirectory_v1beta1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO - - -class RegistrationServiceGrpcTransport(RegistrationServiceTransport): - """gRPC backend transport for RegistrationService. - - Service Directory API for registering services. It defines the - following resource model: - - - The API has a collection of - [Namespace][google.cloud.servicedirectory.v1beta1.Namespace] - resources, named ``projects/*/locations/*/namespaces/*``. - - - Each Namespace has a collection of - [Service][google.cloud.servicedirectory.v1beta1.Service] - resources, named - ``projects/*/locations/*/namespaces/*/services/*``. - - - Each Service has a collection of - [Endpoint][google.cloud.servicedirectory.v1beta1.Endpoint] - resources, named - ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. - - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 create_namespace(self) -> Callable[ - [registration_service.CreateNamespaceRequest], - gcs_namespace.Namespace]: - r"""Return a callable for the create namespace method over gRPC. - - Creates a namespace, and returns the new namespace. - - Returns: - Callable[[~.CreateNamespaceRequest], - ~.Namespace]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['create_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateNamespace', - request_serializer=registration_service.CreateNamespaceRequest.serialize, - response_deserializer=gcs_namespace.Namespace.deserialize, - ) - return self._stubs['create_namespace'] - - @property - def list_namespaces(self) -> Callable[ - [registration_service.ListNamespacesRequest], - registration_service.ListNamespacesResponse]: - r"""Return a callable for the list namespaces method over gRPC. - - Lists all namespaces. - - Returns: - Callable[[~.ListNamespacesRequest], - ~.ListNamespacesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespaces' not in self._stubs: - self._stubs['list_namespaces'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListNamespaces', - request_serializer=registration_service.ListNamespacesRequest.serialize, - response_deserializer=registration_service.ListNamespacesResponse.deserialize, - ) - return self._stubs['list_namespaces'] - - @property - def get_namespace(self) -> Callable[ - [registration_service.GetNamespaceRequest], - namespace.Namespace]: - r"""Return a callable for the get namespace method over gRPC. - - Gets a namespace. - - Returns: - Callable[[~.GetNamespaceRequest], - ~.Namespace]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['get_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetNamespace', - request_serializer=registration_service.GetNamespaceRequest.serialize, - response_deserializer=namespace.Namespace.deserialize, - ) - return self._stubs['get_namespace'] - - @property - def update_namespace(self) -> Callable[ - [registration_service.UpdateNamespaceRequest], - gcs_namespace.Namespace]: - r"""Return a callable for the update namespace method over gRPC. - - Updates a namespace. - - Returns: - Callable[[~.UpdateNamespaceRequest], - ~.Namespace]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['update_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateNamespace', - request_serializer=registration_service.UpdateNamespaceRequest.serialize, - response_deserializer=gcs_namespace.Namespace.deserialize, - ) - return self._stubs['update_namespace'] - - @property - def delete_namespace(self) -> Callable[ - [registration_service.DeleteNamespaceRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete namespace method over gRPC. - - Deletes a namespace. This also deletes all services - and endpoints in the namespace. - - Returns: - Callable[[~.DeleteNamespaceRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_namespace' not in self._stubs: - self._stubs['delete_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteNamespace', - request_serializer=registration_service.DeleteNamespaceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_namespace'] - - @property - def create_service(self) -> Callable[ - [registration_service.CreateServiceRequest], - gcs_service.Service]: - r"""Return a callable for the create service method over gRPC. - - Creates a service, and returns the new service. - - Returns: - Callable[[~.CreateServiceRequest], - ~.Service]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_service' not in self._stubs: - self._stubs['create_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateService', - request_serializer=registration_service.CreateServiceRequest.serialize, - response_deserializer=gcs_service.Service.deserialize, - ) - return self._stubs['create_service'] - - @property - def list_services(self) -> Callable[ - [registration_service.ListServicesRequest], - registration_service.ListServicesResponse]: - r"""Return a callable for the list services method over gRPC. - - Lists all services belonging to a namespace. - - Returns: - Callable[[~.ListServicesRequest], - ~.ListServicesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_services' not in self._stubs: - self._stubs['list_services'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListServices', - request_serializer=registration_service.ListServicesRequest.serialize, - response_deserializer=registration_service.ListServicesResponse.deserialize, - ) - return self._stubs['list_services'] - - @property - def get_service(self) -> Callable[ - [registration_service.GetServiceRequest], - service.Service]: - r"""Return a callable for the get service method over gRPC. - - Gets a service. - - Returns: - Callable[[~.GetServiceRequest], - ~.Service]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_service' not in self._stubs: - self._stubs['get_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetService', - request_serializer=registration_service.GetServiceRequest.serialize, - response_deserializer=service.Service.deserialize, - ) - return self._stubs['get_service'] - - @property - def update_service(self) -> Callable[ - [registration_service.UpdateServiceRequest], - gcs_service.Service]: - r"""Return a callable for the update service method over gRPC. - - Updates a service. - - Returns: - Callable[[~.UpdateServiceRequest], - ~.Service]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_service' not in self._stubs: - self._stubs['update_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateService', - request_serializer=registration_service.UpdateServiceRequest.serialize, - response_deserializer=gcs_service.Service.deserialize, - ) - return self._stubs['update_service'] - - @property - def delete_service(self) -> Callable[ - [registration_service.DeleteServiceRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete service method over gRPC. - - Deletes a service. This also deletes all endpoints - associated with the service. - - Returns: - Callable[[~.DeleteServiceRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_service' not in self._stubs: - self._stubs['delete_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteService', - request_serializer=registration_service.DeleteServiceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_service'] - - @property - def create_endpoint(self) -> Callable[ - [registration_service.CreateEndpointRequest], - gcs_endpoint.Endpoint]: - r"""Return a callable for the create endpoint method over gRPC. - - Creates an endpoint, and returns the new endpoint. - - Returns: - Callable[[~.CreateEndpointRequest], - ~.Endpoint]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['create_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateEndpoint', - request_serializer=registration_service.CreateEndpointRequest.serialize, - response_deserializer=gcs_endpoint.Endpoint.deserialize, - ) - return self._stubs['create_endpoint'] - - @property - def list_endpoints(self) -> Callable[ - [registration_service.ListEndpointsRequest], - registration_service.ListEndpointsResponse]: - r"""Return a callable for the list endpoints method over gRPC. - - Lists all endpoints. - - Returns: - Callable[[~.ListEndpointsRequest], - ~.ListEndpointsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoints' not in self._stubs: - self._stubs['list_endpoints'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListEndpoints', - request_serializer=registration_service.ListEndpointsRequest.serialize, - response_deserializer=registration_service.ListEndpointsResponse.deserialize, - ) - return self._stubs['list_endpoints'] - - @property - def get_endpoint(self) -> Callable[ - [registration_service.GetEndpointRequest], - endpoint.Endpoint]: - r"""Return a callable for the get endpoint method over gRPC. - - Gets an endpoint. - - Returns: - Callable[[~.GetEndpointRequest], - ~.Endpoint]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['get_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetEndpoint', - request_serializer=registration_service.GetEndpointRequest.serialize, - response_deserializer=endpoint.Endpoint.deserialize, - ) - return self._stubs['get_endpoint'] - - @property - def update_endpoint(self) -> Callable[ - [registration_service.UpdateEndpointRequest], - gcs_endpoint.Endpoint]: - r"""Return a callable for the update endpoint method over gRPC. - - Updates an endpoint. - - Returns: - Callable[[~.UpdateEndpointRequest], - ~.Endpoint]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['update_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateEndpoint', - request_serializer=registration_service.UpdateEndpointRequest.serialize, - response_deserializer=gcs_endpoint.Endpoint.deserialize, - ) - return self._stubs['update_endpoint'] - - @property - def delete_endpoint(self) -> Callable[ - [registration_service.DeleteEndpointRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete endpoint method over gRPC. - - Deletes an endpoint. - - Returns: - Callable[[~.DeleteEndpointRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_endpoint' not in self._stubs: - self._stubs['delete_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteEndpoint', - request_serializer=registration_service.DeleteEndpointRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_endpoint'] - - @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 Policy for a resource (namespace or - service only). - - 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.cloud.servicedirectory.v1beta1.RegistrationService/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 Policy for a resource (namespace or - service only). - - 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.cloud.servicedirectory.v1beta1.RegistrationService/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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 IAM permissions for a resource (namespace or - service only). - - 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.cloud.servicedirectory.v1beta1.RegistrationService/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'RegistrationServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py deleted file mode 100644 index c729bdaa..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,730 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.servicedirectory_v1beta1.types import endpoint -from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1beta1.types import namespace -from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1beta1.types import registration_service -from google.cloud.servicedirectory_v1beta1.types import service -from google.cloud.servicedirectory_v1beta1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import RegistrationServiceGrpcTransport - - -class RegistrationServiceGrpcAsyncIOTransport(RegistrationServiceTransport): - """gRPC AsyncIO backend transport for RegistrationService. - - Service Directory API for registering services. It defines the - following resource model: - - - The API has a collection of - [Namespace][google.cloud.servicedirectory.v1beta1.Namespace] - resources, named ``projects/*/locations/*/namespaces/*``. - - - Each Namespace has a collection of - [Service][google.cloud.servicedirectory.v1beta1.Service] - resources, named - ``projects/*/locations/*/namespaces/*/services/*``. - - - Each Service has a collection of - [Endpoint][google.cloud.servicedirectory.v1beta1.Endpoint] - resources, named - ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. - - 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 = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'servicedirectory.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_namespace(self) -> Callable[ - [registration_service.CreateNamespaceRequest], - Awaitable[gcs_namespace.Namespace]]: - r"""Return a callable for the create namespace method over gRPC. - - Creates a namespace, and returns the new namespace. - - Returns: - Callable[[~.CreateNamespaceRequest], - Awaitable[~.Namespace]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['create_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateNamespace', - request_serializer=registration_service.CreateNamespaceRequest.serialize, - response_deserializer=gcs_namespace.Namespace.deserialize, - ) - return self._stubs['create_namespace'] - - @property - def list_namespaces(self) -> Callable[ - [registration_service.ListNamespacesRequest], - Awaitable[registration_service.ListNamespacesResponse]]: - r"""Return a callable for the list namespaces method over gRPC. - - Lists all namespaces. - - Returns: - Callable[[~.ListNamespacesRequest], - Awaitable[~.ListNamespacesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespaces' not in self._stubs: - self._stubs['list_namespaces'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListNamespaces', - request_serializer=registration_service.ListNamespacesRequest.serialize, - response_deserializer=registration_service.ListNamespacesResponse.deserialize, - ) - return self._stubs['list_namespaces'] - - @property - def get_namespace(self) -> Callable[ - [registration_service.GetNamespaceRequest], - Awaitable[namespace.Namespace]]: - r"""Return a callable for the get namespace method over gRPC. - - Gets a namespace. - - Returns: - Callable[[~.GetNamespaceRequest], - Awaitable[~.Namespace]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['get_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetNamespace', - request_serializer=registration_service.GetNamespaceRequest.serialize, - response_deserializer=namespace.Namespace.deserialize, - ) - return self._stubs['get_namespace'] - - @property - def update_namespace(self) -> Callable[ - [registration_service.UpdateNamespaceRequest], - Awaitable[gcs_namespace.Namespace]]: - r"""Return a callable for the update namespace method over gRPC. - - Updates a namespace. - - Returns: - Callable[[~.UpdateNamespaceRequest], - Awaitable[~.Namespace]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_namespace' not in self._stubs: - self._stubs['update_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateNamespace', - request_serializer=registration_service.UpdateNamespaceRequest.serialize, - response_deserializer=gcs_namespace.Namespace.deserialize, - ) - return self._stubs['update_namespace'] - - @property - def delete_namespace(self) -> Callable[ - [registration_service.DeleteNamespaceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete namespace method over gRPC. - - Deletes a namespace. This also deletes all services - and endpoints in the namespace. - - Returns: - Callable[[~.DeleteNamespaceRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_namespace' not in self._stubs: - self._stubs['delete_namespace'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteNamespace', - request_serializer=registration_service.DeleteNamespaceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_namespace'] - - @property - def create_service(self) -> Callable[ - [registration_service.CreateServiceRequest], - Awaitable[gcs_service.Service]]: - r"""Return a callable for the create service method over gRPC. - - Creates a service, and returns the new service. - - Returns: - Callable[[~.CreateServiceRequest], - Awaitable[~.Service]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_service' not in self._stubs: - self._stubs['create_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateService', - request_serializer=registration_service.CreateServiceRequest.serialize, - response_deserializer=gcs_service.Service.deserialize, - ) - return self._stubs['create_service'] - - @property - def list_services(self) -> Callable[ - [registration_service.ListServicesRequest], - Awaitable[registration_service.ListServicesResponse]]: - r"""Return a callable for the list services method over gRPC. - - Lists all services belonging to a namespace. - - Returns: - Callable[[~.ListServicesRequest], - Awaitable[~.ListServicesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_services' not in self._stubs: - self._stubs['list_services'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListServices', - request_serializer=registration_service.ListServicesRequest.serialize, - response_deserializer=registration_service.ListServicesResponse.deserialize, - ) - return self._stubs['list_services'] - - @property - def get_service(self) -> Callable[ - [registration_service.GetServiceRequest], - Awaitable[service.Service]]: - r"""Return a callable for the get service method over gRPC. - - Gets a service. - - Returns: - Callable[[~.GetServiceRequest], - Awaitable[~.Service]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_service' not in self._stubs: - self._stubs['get_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetService', - request_serializer=registration_service.GetServiceRequest.serialize, - response_deserializer=service.Service.deserialize, - ) - return self._stubs['get_service'] - - @property - def update_service(self) -> Callable[ - [registration_service.UpdateServiceRequest], - Awaitable[gcs_service.Service]]: - r"""Return a callable for the update service method over gRPC. - - Updates a service. - - Returns: - Callable[[~.UpdateServiceRequest], - Awaitable[~.Service]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_service' not in self._stubs: - self._stubs['update_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateService', - request_serializer=registration_service.UpdateServiceRequest.serialize, - response_deserializer=gcs_service.Service.deserialize, - ) - return self._stubs['update_service'] - - @property - def delete_service(self) -> Callable[ - [registration_service.DeleteServiceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete service method over gRPC. - - Deletes a service. This also deletes all endpoints - associated with the service. - - Returns: - Callable[[~.DeleteServiceRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_service' not in self._stubs: - self._stubs['delete_service'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteService', - request_serializer=registration_service.DeleteServiceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_service'] - - @property - def create_endpoint(self) -> Callable[ - [registration_service.CreateEndpointRequest], - Awaitable[gcs_endpoint.Endpoint]]: - r"""Return a callable for the create endpoint method over gRPC. - - Creates an endpoint, and returns the new endpoint. - - Returns: - Callable[[~.CreateEndpointRequest], - Awaitable[~.Endpoint]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['create_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateEndpoint', - request_serializer=registration_service.CreateEndpointRequest.serialize, - response_deserializer=gcs_endpoint.Endpoint.deserialize, - ) - return self._stubs['create_endpoint'] - - @property - def list_endpoints(self) -> Callable[ - [registration_service.ListEndpointsRequest], - Awaitable[registration_service.ListEndpointsResponse]]: - r"""Return a callable for the list endpoints method over gRPC. - - Lists all endpoints. - - Returns: - Callable[[~.ListEndpointsRequest], - Awaitable[~.ListEndpointsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoints' not in self._stubs: - self._stubs['list_endpoints'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/ListEndpoints', - request_serializer=registration_service.ListEndpointsRequest.serialize, - response_deserializer=registration_service.ListEndpointsResponse.deserialize, - ) - return self._stubs['list_endpoints'] - - @property - def get_endpoint(self) -> Callable[ - [registration_service.GetEndpointRequest], - Awaitable[endpoint.Endpoint]]: - r"""Return a callable for the get endpoint method over gRPC. - - Gets an endpoint. - - Returns: - Callable[[~.GetEndpointRequest], - Awaitable[~.Endpoint]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['get_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/GetEndpoint', - request_serializer=registration_service.GetEndpointRequest.serialize, - response_deserializer=endpoint.Endpoint.deserialize, - ) - return self._stubs['get_endpoint'] - - @property - def update_endpoint(self) -> Callable[ - [registration_service.UpdateEndpointRequest], - Awaitable[gcs_endpoint.Endpoint]]: - r"""Return a callable for the update endpoint method over gRPC. - - Updates an endpoint. - - Returns: - Callable[[~.UpdateEndpointRequest], - Awaitable[~.Endpoint]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint' not in self._stubs: - self._stubs['update_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateEndpoint', - request_serializer=registration_service.UpdateEndpointRequest.serialize, - response_deserializer=gcs_endpoint.Endpoint.deserialize, - ) - return self._stubs['update_endpoint'] - - @property - def delete_endpoint(self) -> Callable[ - [registration_service.DeleteEndpointRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete endpoint method over gRPC. - - Deletes an endpoint. - - Returns: - Callable[[~.DeleteEndpointRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_endpoint' not in self._stubs: - self._stubs['delete_endpoint'] = self.grpc_channel.unary_unary( - '/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteEndpoint', - request_serializer=registration_service.DeleteEndpointRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_endpoint'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM Policy for a resource (namespace or - service only). - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.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.cloud.servicedirectory.v1beta1.RegistrationService/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the IAM Policy for a resource (namespace or - service only). - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.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.cloud.servicedirectory.v1beta1.RegistrationService/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Tests IAM permissions for a resource (namespace or - service only). - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.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.cloud.servicedirectory.v1beta1.RegistrationService/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'RegistrationServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/__init__.py deleted file mode 100644 index acf22489..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/__init__.py +++ /dev/null @@ -1,74 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .endpoint import ( - Endpoint, -) -from .lookup_service import ( - ResolveServiceRequest, - ResolveServiceResponse, -) -from .namespace import ( - Namespace, -) -from .registration_service import ( - CreateEndpointRequest, - CreateNamespaceRequest, - CreateServiceRequest, - DeleteEndpointRequest, - DeleteNamespaceRequest, - DeleteServiceRequest, - GetEndpointRequest, - GetNamespaceRequest, - GetServiceRequest, - ListEndpointsRequest, - ListEndpointsResponse, - ListNamespacesRequest, - ListNamespacesResponse, - ListServicesRequest, - ListServicesResponse, - UpdateEndpointRequest, - UpdateNamespaceRequest, - UpdateServiceRequest, -) -from .service import ( - Service, -) - -__all__ = ( - 'Endpoint', - 'ResolveServiceRequest', - 'ResolveServiceResponse', - 'Namespace', - 'CreateEndpointRequest', - 'CreateNamespaceRequest', - 'CreateServiceRequest', - 'DeleteEndpointRequest', - 'DeleteNamespaceRequest', - 'DeleteServiceRequest', - 'GetEndpointRequest', - 'GetNamespaceRequest', - 'GetServiceRequest', - 'ListEndpointsRequest', - 'ListEndpointsResponse', - 'ListNamespacesRequest', - 'ListNamespacesResponse', - 'ListServicesRequest', - 'ListServicesResponse', - 'UpdateEndpointRequest', - 'UpdateNamespaceRequest', - 'UpdateServiceRequest', - 'Service', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/endpoint.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/endpoint.py deleted file mode 100644 index 33890a47..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/endpoint.py +++ /dev/null @@ -1,130 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.servicedirectory.v1beta1', - manifest={ - 'Endpoint', - }, -) - - -class Endpoint(proto.Message): - r"""An individual endpoint that provides a - [service][google.cloud.servicedirectory.v1beta1.Service]. The - service must already exist to create an endpoint. - - Attributes: - name (str): - Immutable. The resource name for the endpoint in the format - ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. - address (str): - Optional. An IPv4 or IPv6 address. Service Directory rejects - bad addresses like: - - - ``8.8.8`` - - ``8.8.8.8:53`` - - ``test:bad:address`` - - ``[::1]`` - - ``[::1]:8080`` - - Limited to 45 characters. - port (int): - Optional. Service Directory rejects values outside of - ``[0, 65535]``. - metadata (Sequence[google.cloud.servicedirectory_v1beta1.types.Endpoint.MetadataEntry]): - Optional. Metadata for the endpoint. This data can be - consumed by service clients. - - Restrictions: - - - The entire metadata dictionary may contain up to 512 - characters, spread accoss all key-value pairs. Metadata - that goes beyond this limit are rejected - - Valid metadata keys have two segments: an optional prefix - and name, separated by a slash (/). The name segment is - required and must be 63 characters or less, beginning and - ending with an alphanumeric character ([a-z0-9A-Z]) with - dashes (-), underscores (_), dots (.), and alphanumerics - between. The prefix is optional. If specified, the prefix - must be a DNS subdomain: a series of DNS labels separated - by dots (.), not longer than 253 characters in total, - followed by a slash (/). Metadata that fails to meet - these requirements are rejected - - The ``(*.)google.com/`` and ``(*.)googleapis.com/`` - prefixes are reserved for system metadata managed by - Service Directory. If the user tries to write to these - keyspaces, those entries are silently ignored by the - system - - Note: This field is equivalent to the ``annotations`` field - in the v1 API. They have the same syntax and read/write to - the same location in Service Directory. - network (str): - Immutable. The Google Compute Engine network (VPC) of the - endpoint in the format - ``projects//locations/global/networks/*``. - - The project must be specified by project number (project id - is rejected). Incorrectly formatted networks are rejected, - but no other validation is performed on this field (ex. - network or project existence, reachability, or permissions). - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the endpoint - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the endpoint - was last updated. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - address = proto.Field( - proto.STRING, - number=2, - ) - port = proto.Field( - proto.INT32, - number=3, - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - network = proto.Field( - proto.STRING, - number=5, - ) - create_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/lookup_service.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/lookup_service.py deleted file mode 100644 index 01754f85..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/lookup_service.py +++ /dev/null @@ -1,120 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.cloud.servicedirectory_v1beta1.types import service as gcs_service - - -__protobuf__ = proto.module( - package='google.cloud.servicedirectory.v1beta1', - manifest={ - 'ResolveServiceRequest', - 'ResolveServiceResponse', - }, -) - - -class ResolveServiceRequest(proto.Message): - r"""The request message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. - Looks up a service by its name, returns the service and its - endpoints. - - Attributes: - name (str): - Required. The name of the service to resolve. - max_endpoints (int): - Optional. The maximum number of endpoints to - return. Defaults to 25. Maximum is 100. If a - value less than one is specified, the Default is - used. If a value greater than the Maximum is - specified, the Maximum is used. - endpoint_filter (str): - Optional. The filter applied to the endpoints of the - resolved service. - - General ``filter`` string syntax: - `` ()`` - - - ```` can be ``name``, ``address``, ``port``, or - ``metadata.`` for map field - - ```` can be ``<``, ``>``, ``<=``, ``>=``, - ``!=``, ``=``, ``:``. Of which ``:`` means ``HAS``, and - is roughly the same as ``=`` - - ```` must be the same data type as field - - ```` can be ``AND``, ``OR``, ``NOT`` - - Examples of valid filters: - - - ``metadata.owner`` returns endpoints that have a - annotation with the key ``owner``, this is the same as - ``metadata:owner`` - - ``metadata.protocol=gRPC`` returns endpoints that have - key/value ``protocol=gRPC`` - - ``address=192.108.1.105`` returns endpoints that have - this address - - ``port>8080`` returns endpoints that have port number - larger than 8080 - - - - ``name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/my-service/endpoints/endpoint-c`` - returns endpoints that have name that is alphabetically - later than the string, so "endpoint-e" is returned but - "endpoint-a" is not - - - ``metadata.owner!=sd AND metadata.foo=bar`` returns - endpoints that have ``owner`` in annotation key but value - is not ``sd`` AND have key/value ``foo=bar`` - - ``doesnotexist.foo=bar`` returns an empty list. Note that - endpoint doesn't have a field called "doesnotexist". - Since the filter does not match any endpoint, it returns - no results - - For more information about filtering, see `API - Filtering `__. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - max_endpoints = proto.Field( - proto.INT32, - number=2, - ) - endpoint_filter = proto.Field( - proto.STRING, - number=3, - ) - - -class ResolveServiceResponse(proto.Message): - r"""The response message for - [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. - - Attributes: - service (google.cloud.servicedirectory_v1beta1.types.Service): - - """ - - service = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_service.Service, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/namespace.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/namespace.py deleted file mode 100644 index 7e6d6d0c..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/namespace.py +++ /dev/null @@ -1,73 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.servicedirectory.v1beta1', - manifest={ - 'Namespace', - }, -) - - -class Namespace(proto.Message): - r"""A container for - [services][google.cloud.servicedirectory.v1beta1.Service]. - Namespaces allow administrators to group services together and - define permissions for a collection of services. - - Attributes: - name (str): - Immutable. The resource name for the namespace in the format - ``projects/*/locations/*/namespaces/*``. - labels (Sequence[google.cloud.servicedirectory_v1beta1.types.Namespace.LabelsEntry]): - Optional. Resource labels associated with - this namespace. No more than 64 user labels can - be associated with a given resource. Label keys - and values can be no longer than 63 characters. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the namespace - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the namespace - was last updated. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/registration_service.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/registration_service.py deleted file mode 100644 index 4a5d7f32..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/registration_service.py +++ /dev/null @@ -1,675 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1beta1.types import service as gcs_service -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.servicedirectory.v1beta1', - manifest={ - 'CreateNamespaceRequest', - 'ListNamespacesRequest', - 'ListNamespacesResponse', - 'GetNamespaceRequest', - 'UpdateNamespaceRequest', - 'DeleteNamespaceRequest', - 'CreateServiceRequest', - 'ListServicesRequest', - 'ListServicesResponse', - 'GetServiceRequest', - 'UpdateServiceRequest', - 'DeleteServiceRequest', - 'CreateEndpointRequest', - 'ListEndpointsRequest', - 'ListEndpointsResponse', - 'GetEndpointRequest', - 'UpdateEndpointRequest', - 'DeleteEndpointRequest', - }, -) - - -class CreateNamespaceRequest(proto.Message): - r"""The request message for - [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateNamespace]. - - Attributes: - parent (str): - Required. The resource name of the project - and location the namespace will be created in. - namespace_id (str): - Required. The Resource ID must be 1-63 characters long, and - comply with RFC1035. Specifically, the name must be 1-63 - characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first - character must be a lowercase letter, and all following - characters must be a dash, lowercase letter, or digit, - except the last character, which cannot be a dash. - namespace (google.cloud.servicedirectory_v1beta1.types.Namespace): - Required. A namespace with initial fields - set. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - namespace_id = proto.Field( - proto.STRING, - number=2, - ) - namespace = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_namespace.Namespace, - ) - - -class ListNamespacesRequest(proto.Message): - r"""The request message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. - - Attributes: - parent (str): - Required. The resource name of the project - and location whose namespaces you'd like to - list. - page_size (int): - Optional. The maximum number of items to - return. - page_token (str): - Optional. The next_page_token value returned from a previous - List request, if any. - filter (str): - Optional. The filter to list results by. - - General ``filter`` string syntax: - `` ()`` - - - ```` can be ``name`` or ``labels.`` for map - field - - ```` can be ``<``, ``>``, ``<=``, ``>=``, - ``!=``, ``=``, ``:``. Of which ``:`` means ``HAS``, and - is roughly the same as ``=`` - - ```` must be the same data type as field - - ```` can be ``AND``, ``OR``, ``NOT`` - - Examples of valid filters: - - - ``labels.owner`` returns namespaces that have a label - with the key ``owner``, this is the same as - ``labels:owner`` - - ``labels.owner=sd`` returns namespaces that have - key/value ``owner=sd`` - - ``name>projects/my-project/locations/us-east1/namespaces/namespace-c`` - returns namespaces that have name that is alphabetically - later than the string, so "namespace-e" is returned but - "namespace-a" is not - - ``labels.owner!=sd AND labels.foo=bar`` returns - namespaces that have ``owner`` in label key but value is - not ``sd`` AND have key/value ``foo=bar`` - - ``doesnotexist.foo=bar`` returns an empty list. Note that - namespace doesn't have a field called "doesnotexist". - Since the filter does not match any namespaces, it - returns no results - - For more information about filtering, see `API - Filtering `__. - order_by (str): - Optional. The order to list results by. - - General ``order_by`` string syntax: - `` () (,)`` - - - ```` allows value: ``name`` - - ```` ascending or descending order by - ````. If this is left blank, ``asc`` is used - - Note that an empty ``order_by`` string results in default - order, which is order by ``name`` in ascending order. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - order_by = proto.Field( - proto.STRING, - number=5, - ) - - -class ListNamespacesResponse(proto.Message): - r"""The response message for - [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. - - Attributes: - namespaces (Sequence[google.cloud.servicedirectory_v1beta1.types.Namespace]): - The list of namespaces. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - namespaces = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_namespace.Namespace, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetNamespaceRequest(proto.Message): - r"""The request message for - [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.GetNamespace]. - - Attributes: - name (str): - Required. The name of the namespace to - retrieve. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateNamespaceRequest(proto.Message): - r"""The request message for - [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateNamespace]. - - Attributes: - namespace (google.cloud.servicedirectory_v1beta1.types.Namespace): - Required. The updated namespace. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - namespace = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_namespace.Namespace, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteNamespaceRequest(proto.Message): - r"""The request message for - [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteNamespace]. - - Attributes: - name (str): - Required. The name of the namespace to - delete. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateServiceRequest(proto.Message): - r"""The request message for - [RegistrationService.CreateService][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateService]. - - Attributes: - parent (str): - Required. The resource name of the namespace - this service will belong to. - service_id (str): - Required. The Resource ID must be 1-63 characters long, and - comply with RFC1035. Specifically, the name must be 1-63 - characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first - character must be a lowercase letter, and all following - characters must be a dash, lowercase letter, or digit, - except the last character, which cannot be a dash. - service (google.cloud.servicedirectory_v1beta1.types.Service): - Required. A service with initial fields set. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - service_id = proto.Field( - proto.STRING, - number=2, - ) - service = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_service.Service, - ) - - -class ListServicesRequest(proto.Message): - r"""The request message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. - - Attributes: - parent (str): - Required. The resource name of the namespace - whose services you'd like to list. - page_size (int): - Optional. The maximum number of items to - return. - page_token (str): - Optional. The next_page_token value returned from a previous - List request, if any. - filter (str): - Optional. The filter to list results by. - - General ``filter`` string syntax: - `` ()`` - - - ```` can be ``name`` or ``metadata.`` for map - field - - ```` can be ``<``, ``>``, ``<=``, ``>=``, - ``!=``, ``=``, ``:``. Of which ``:`` means ``HAS``, and - is roughly the same as ``=`` - - ```` must be the same data type as field - - ```` can be ``AND``, ``OR``, ``NOT`` - - Examples of valid filters: - - - ``metadata.owner`` returns services that have a metadata - with the key ``owner``, this is the same as - ``metadata:owner`` - - ``metadata.protocol=gRPC`` returns services that have - key/value ``protocol=gRPC`` - - - - ``name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/service-c`` - returns services that have name that is alphabetically later - than the string, so "service-e" is returned but "service-a" - is not - - - ``metadata.owner!=sd AND metadata.foo=bar`` returns - services that have ``owner`` in metadata key but value is - not ``sd`` AND have key/value ``foo=bar`` - - ``doesnotexist.foo=bar`` returns an empty list. Note that - service doesn't have a field called "doesnotexist". Since - the filter does not match any services, it returns no - results - - For more information about filtering, see `API - Filtering `__. - order_by (str): - Optional. The order to list results by. - - General ``order_by`` string syntax: - `` () (,)`` - - - ```` allows value: ``name`` - - ```` ascending or descending order by - ````. If this is left blank, ``asc`` is used - - Note that an empty ``order_by`` string results in default - order, which is order by ``name`` in ascending order. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - order_by = proto.Field( - proto.STRING, - number=5, - ) - - -class ListServicesResponse(proto.Message): - r"""The response message for - [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. - - Attributes: - services (Sequence[google.cloud.servicedirectory_v1beta1.types.Service]): - The list of services. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - services = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_service.Service, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetServiceRequest(proto.Message): - r"""The request message for - [RegistrationService.GetService][google.cloud.servicedirectory.v1beta1.RegistrationService.GetService]. - This should not be used for looking up a service. Insead, use the - ``resolve`` method as it contains all endpoints and associated - metadata. - - Attributes: - name (str): - Required. The name of the service to get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateServiceRequest(proto.Message): - r"""The request message for - [RegistrationService.UpdateService][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateService]. - - Attributes: - service (google.cloud.servicedirectory_v1beta1.types.Service): - Required. The updated service. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - service = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_service.Service, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteServiceRequest(proto.Message): - r"""The request message for - [RegistrationService.DeleteService][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteService]. - - Attributes: - name (str): - Required. The name of the service to delete. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateEndpointRequest(proto.Message): - r"""The request message for - [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateEndpoint]. - - Attributes: - parent (str): - Required. The resource name of the service - that this endpoint provides. - endpoint_id (str): - Required. The Resource ID must be 1-63 characters long, and - comply with RFC1035. Specifically, the name must be 1-63 - characters long and match the regular expression - ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first - character must be a lowercase letter, and all following - characters must be a dash, lowercase letter, or digit, - except the last character, which cannot be a dash. - endpoint (google.cloud.servicedirectory_v1beta1.types.Endpoint): - Required. A endpoint with initial fields set. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - endpoint_id = proto.Field( - proto.STRING, - number=2, - ) - endpoint = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_endpoint.Endpoint, - ) - - -class ListEndpointsRequest(proto.Message): - r"""The request message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. - - Attributes: - parent (str): - Required. The resource name of the service - whose endpoints you'd like to list. - page_size (int): - Optional. The maximum number of items to - return. - page_token (str): - Optional. The next_page_token value returned from a previous - List request, if any. - filter (str): - Optional. The filter to list results by. - - General ``filter`` string syntax: - `` ()`` - - - ```` can be ``name``, ``address``, ``port``, or - ``metadata.`` for map field - - ```` can be ``<``, ``>``, ``<=``, ``>=``, - ``!=``, ``=``, ``:``. Of which ``:`` means ``HAS``, and - is roughly the same as ``=`` - - ```` must be the same data type as field - - ```` can be ``AND``, ``OR``, ``NOT`` - - Examples of valid filters: - - - ``metadata.owner`` returns endpoints that have a metadata - with the key ``owner``, this is the same as - ``metadata:owner`` - - ``metadata.protocol=gRPC`` returns endpoints that have - key/value ``protocol=gRPC`` - - ``address=192.108.1.105`` returns endpoints that have - this address - - ``port>8080`` returns endpoints that have port number - larger than 8080 - - - - ``name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/my-service/endpoints/endpoint-c`` - returns endpoints that have name that is alphabetically - later than the string, so "endpoint-e" is returned but - "endpoint-a" is not - - - ``metadata.owner!=sd AND metadata.foo=bar`` returns - endpoints that have ``owner`` in metadata key but value - is not ``sd`` AND have key/value ``foo=bar`` - - ``doesnotexist.foo=bar`` returns an empty list. Note that - endpoint doesn't have a field called "doesnotexist". - Since the filter does not match any endpoints, it returns - no results - - For more information about filtering, see `API - Filtering `__. - order_by (str): - Optional. The order to list results by. - - General ``order_by`` string syntax: - `` () (,)`` - - - ```` allows values: ``name``, ``address``, - ``port`` - - ```` ascending or descending order by - ````. If this is left blank, ``asc`` is used - - Note that an empty ``order_by`` string results in default - order, which is order by ``name`` in ascending order. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - order_by = proto.Field( - proto.STRING, - number=5, - ) - - -class ListEndpointsResponse(proto.Message): - r"""The response message for - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. - - Attributes: - endpoints (Sequence[google.cloud.servicedirectory_v1beta1.types.Endpoint]): - The list of endpoints. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - endpoints = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_endpoint.Endpoint, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetEndpointRequest(proto.Message): - r"""The request message for - [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.GetEndpoint]. - This should not be used to lookup endpoints at runtime. Instead, use - the ``resolve`` method. - - Attributes: - name (str): - Required. The name of the endpoint to get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateEndpointRequest(proto.Message): - r"""The request message for - [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateEndpoint]. - - Attributes: - endpoint (google.cloud.servicedirectory_v1beta1.types.Endpoint): - Required. The updated endpoint. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - endpoint = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_endpoint.Endpoint, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteEndpointRequest(proto.Message): - r"""The request message for - [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteEndpoint]. - - Attributes: - name (str): - Required. The name of the endpoint to delete. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/service.py b/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/service.py deleted file mode 100644 index efa98fbe..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/servicedirectory_v1beta1/types/service.py +++ /dev/null @@ -1,111 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.cloud.servicedirectory_v1beta1.types import endpoint -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.servicedirectory.v1beta1', - manifest={ - 'Service', - }, -) - - -class Service(proto.Message): - r"""An individual service. A service contains a name and optional - metadata. A service must exist before - [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] can be - added to it. - - Attributes: - name (str): - Immutable. The resource name for the service in the format - ``projects/*/locations/*/namespaces/*/services/*``. - metadata (Sequence[google.cloud.servicedirectory_v1beta1.types.Service.MetadataEntry]): - Optional. Metadata for the service. This data can be - consumed by service clients. - - Restrictions: - - - The entire metadata dictionary may contain up to 2000 - characters, spread accoss all key-value pairs. Metadata - that goes beyond this limit are rejected - - Valid metadata keys have two segments: an optional prefix - and name, separated by a slash (/). The name segment is - required and must be 63 characters or less, beginning and - ending with an alphanumeric character ([a-z0-9A-Z]) with - dashes (-), underscores (_), dots (.), and alphanumerics - between. The prefix is optional. If specified, the prefix - must be a DNS subdomain: a series of DNS labels separated - by dots (.), not longer than 253 characters in total, - followed by a slash (/). Metadata that fails to meet - these requirements are rejected - - The ``(*.)google.com/`` and ``(*.)googleapis.com/`` - prefixes are reserved for system metadata managed by - Service Directory. If the user tries to write to these - keyspaces, those entries are silently ignored by the - system - - Note: This field is equivalent to the ``annotations`` field - in the v1 API. They have the same syntax and read/write to - the same location in Service Directory. - endpoints (Sequence[google.cloud.servicedirectory_v1beta1.types.Endpoint]): - Output only. Endpoints associated with this service. - Returned on - [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. - Control plane clients should use - [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the service - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the service - was last updated. Note: endpoints being - created/deleted/updated within the service are - not considered service updates for the purpose - of this timestamp. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - endpoints = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=endpoint.Endpoint, - ) - create_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py deleted file mode 100644 index f02a62c6..00000000 --- a/owl-bot-staging/v1beta1/noxfile.py +++ /dev/null @@ -1,132 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/servicedirectory_v1beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - '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='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1beta1/scripts/fixup_servicedirectory_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_servicedirectory_v1beta1_keywords.py deleted file mode 100644 index 892e98cf..00000000 --- a/owl-bot-staging/v1beta1/scripts/fixup_servicedirectory_v1beta1_keywords.py +++ /dev/null @@ -1,194 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 servicedirectoryCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_endpoint': ('parent', 'endpoint_id', 'endpoint', ), - 'create_namespace': ('parent', 'namespace_id', 'namespace', ), - 'create_service': ('parent', 'service_id', 'service', ), - 'delete_endpoint': ('name', ), - 'delete_namespace': ('name', ), - 'delete_service': ('name', ), - 'get_endpoint': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_namespace': ('name', ), - 'get_service': ('name', ), - 'list_endpoints': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_namespaces': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_services': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'resolve_service': ('name', 'max_endpoints', 'endpoint_filter', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_endpoint': ('endpoint', 'update_mask', ), - 'update_namespace': ('namespace', 'update_mask', ), - 'update_service': ('service', 'update_mask', ), - } - - 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=servicedirectoryCallTransformer(), -): - """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 servicedirectory 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py deleted file mode 100644 index 0aacc848..00000000 --- a/owl-bot-staging/v1beta1/setup.py +++ /dev/null @@ -1,54 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 setuptools # type: ignore - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-service-directory', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/tests/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py deleted file mode 100644 index 7caa65da..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py +++ /dev/null @@ -1,1176 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -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 path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.servicedirectory_v1beta1.services.lookup_service import LookupServiceAsyncClient -from google.cloud.servicedirectory_v1beta1.services.lookup_service import LookupServiceClient -from google.cloud.servicedirectory_v1beta1.services.lookup_service import transports -from google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.servicedirectory_v1beta1.types import lookup_service -from google.cloud.servicedirectory_v1beta1.types import service -from google.oauth2 import service_account -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert LookupServiceClient._get_default_mtls_endpoint(None) is None - assert LookupServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LookupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LookupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LookupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LookupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - LookupServiceClient, - LookupServiceAsyncClient, -]) -def test_lookup_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.LookupServiceGrpcTransport, "grpc"), - (transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_lookup_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", [ - LookupServiceClient, - LookupServiceAsyncClient, -]) -def test_lookup_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -def test_lookup_service_client_get_transport_class(): - transport = LookupServiceClient.get_transport_class() - available_transports = [ - transports.LookupServiceGrpcTransport, - ] - assert transport in available_transports - - transport = LookupServiceClient.get_transport_class("grpc") - assert transport == transports.LookupServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), - (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(LookupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceClient)) -@mock.patch.object(LookupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceAsyncClient)) -def test_lookup_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(LookupServiceClient, '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(LookupServiceClient, '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(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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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() - 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "true"), - (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "false"), - (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(LookupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceClient)) -@mock.patch.object(LookupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LookupServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_lookup_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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - 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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), - (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_lookup_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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), - (LookupServiceAsyncClient, transports.LookupServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_lookup_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_lookup_service_client_client_options_from_dict(): - with mock.patch('google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = LookupServiceClient( - 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, - ) - - -def test_resolve_service(transport: str = 'grpc', request_type=lookup_service.ResolveServiceRequest): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resolve_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lookup_service.ResolveServiceResponse( - ) - response = client.resolve_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == lookup_service.ResolveServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, lookup_service.ResolveServiceResponse) - - -def test_resolve_service_from_dict(): - test_resolve_service(request_type=dict) - - -def test_resolve_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resolve_service), - '__call__') as call: - client.resolve_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == lookup_service.ResolveServiceRequest() - - -@pytest.mark.asyncio -async def test_resolve_service_async(transport: str = 'grpc_asyncio', request_type=lookup_service.ResolveServiceRequest): - client = LookupServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resolve_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lookup_service.ResolveServiceResponse( - )) - response = await client.resolve_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == lookup_service.ResolveServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, lookup_service.ResolveServiceResponse) - - -@pytest.mark.asyncio -async def test_resolve_service_async_from_dict(): - await test_resolve_service_async(request_type=dict) - - -def test_resolve_service_field_headers(): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = lookup_service.ResolveServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resolve_service), - '__call__') as call: - call.return_value = lookup_service.ResolveServiceResponse() - client.resolve_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_resolve_service_field_headers_async(): - client = LookupServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = lookup_service.ResolveServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resolve_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lookup_service.ResolveServiceResponse()) - await client.resolve_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LookupServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LookupServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LookupServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LookupServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.LookupServiceGrpcTransport, - transports.LookupServiceGrpcAsyncIOTransport, -]) -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_grpc_default(): - # A client should use the gRPC transport by default. - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LookupServiceGrpcTransport, - ) - -def test_lookup_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LookupServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_lookup_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.LookupServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'resolve_service', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -@requires_google_auth_gte_1_25_0 -def test_lookup_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.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LookupServiceTransport( - 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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_lookup_service_base_transport_with_credentials_file_old_google_auth(): - # 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.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LookupServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_lookup_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.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LookupServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_lookup_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) - LookupServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_lookup_service_auth_adc_old_google_auth(): - # 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) - LookupServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LookupServiceGrpcTransport, - transports.LookupServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_lookup_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.LookupServiceGrpcTransport, - transports.LookupServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_lookup_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LookupServiceGrpcTransport, grpc_helpers), - (transports.LookupServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_lookup_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( - "servicedirectory.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="servicedirectory.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) -def test_lookup_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_lookup_service_host_no_port(): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com'), - ) - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -def test_lookup_service_host_with_port(): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com:8000'), - ) - assert client.transport._host == 'servicedirectory.googleapis.com:8000' - -def test_lookup_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LookupServiceGrpcTransport( - 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_lookup_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LookupServiceGrpcAsyncIOTransport( - 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.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) -def test_lookup_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.LookupServiceGrpcTransport, transports.LookupServiceGrpcAsyncIOTransport]) -def test_lookup_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_endpoint_path(): - project = "squid" - location = "clam" - namespace = "whelk" - service = "octopus" - endpoint = "oyster" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) - actual = LookupServiceClient.endpoint_path(project, location, namespace, service, endpoint) - assert expected == actual - - -def test_parse_endpoint_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "namespace": "mussel", - "service": "winkle", - "endpoint": "nautilus", - } - path = LookupServiceClient.endpoint_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_endpoint_path(path) - assert expected == actual - -def test_network_path(): - project = "scallop" - network = "abalone" - expected = "projects/{project}/locations/global/networks/{network}".format(project=project, network=network, ) - actual = LookupServiceClient.network_path(project, network) - assert expected == actual - - -def test_parse_network_path(): - expected = { - "project": "squid", - "network": "clam", - } - path = LookupServiceClient.network_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_network_path(path) - assert expected == actual - -def test_service_path(): - project = "whelk" - location = "octopus" - namespace = "oyster" - service = "nudibranch" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - actual = LookupServiceClient.service_path(project, location, namespace, service) - assert expected == actual - - -def test_parse_service_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "namespace": "winkle", - "service": "nautilus", - } - path = LookupServiceClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_service_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = LookupServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = LookupServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = LookupServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = LookupServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = LookupServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = LookupServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = LookupServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = LookupServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = LookupServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = LookupServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LookupServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.LookupServiceTransport, '_prep_wrapped_messages') as prep: - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.LookupServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = LookupServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = LookupServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = LookupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = LookupServiceClient( - 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() diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py deleted file mode 100644 index 7aa0ac71..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py +++ /dev/null @@ -1,5686 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -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 path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.servicedirectory_v1beta1.services.registration_service import RegistrationServiceAsyncClient -from google.cloud.servicedirectory_v1beta1.services.registration_service import RegistrationServiceClient -from google.cloud.servicedirectory_v1beta1.services.registration_service import pagers -from google.cloud.servicedirectory_v1beta1.services.registration_service import transports -from google.cloud.servicedirectory_v1beta1.services.registration_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.servicedirectory_v1beta1.types import endpoint -from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1beta1.types import namespace -from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1beta1.types import registration_service -from google.cloud.servicedirectory_v1beta1.types import service -from google.cloud.servicedirectory_v1beta1.types import service as gcs_service -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.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert RegistrationServiceClient._get_default_mtls_endpoint(None) is None - assert RegistrationServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RegistrationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RegistrationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RegistrationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RegistrationServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - RegistrationServiceClient, - RegistrationServiceAsyncClient, -]) -def test_registration_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RegistrationServiceGrpcTransport, "grpc"), - (transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_registration_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", [ - RegistrationServiceClient, - RegistrationServiceAsyncClient, -]) -def test_registration_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -def test_registration_service_client_get_transport_class(): - transport = RegistrationServiceClient.get_transport_class() - available_transports = [ - transports.RegistrationServiceGrpcTransport, - ] - assert transport in available_transports - - transport = RegistrationServiceClient.get_transport_class("grpc") - assert transport == transports.RegistrationServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), - (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(RegistrationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceClient)) -@mock.patch.object(RegistrationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceAsyncClient)) -def test_registration_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(RegistrationServiceClient, '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(RegistrationServiceClient, '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(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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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() - 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc", "true"), - (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc", "false"), - (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(RegistrationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceClient)) -@mock.patch.object(RegistrationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistrationServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_registration_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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - 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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), - (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_registration_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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegistrationServiceClient, transports.RegistrationServiceGrpcTransport, "grpc"), - (RegistrationServiceAsyncClient, transports.RegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_registration_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_registration_service_client_client_options_from_dict(): - with mock.patch('google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RegistrationServiceClient( - 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, - ) - - -def test_create_namespace(transport: str = 'grpc', request_type=registration_service.CreateNamespaceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace( - name='name_value', - ) - response = client.create_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_namespace.Namespace) - assert response.name == 'name_value' - - -def test_create_namespace_from_dict(): - test_create_namespace(request_type=dict) - - -def test_create_namespace_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_namespace), - '__call__') as call: - client.create_namespace() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateNamespaceRequest() - - -@pytest.mark.asyncio -async def test_create_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateNamespaceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace( - name='name_value', - )) - response = await client.create_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_namespace.Namespace) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_namespace_async_from_dict(): - await test_create_namespace_async(request_type=dict) - - -def test_create_namespace_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateNamespaceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_namespace), - '__call__') as call: - call.return_value = gcs_namespace.Namespace() - client.create_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_namespace_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateNamespaceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_namespace), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) - await client.create_namespace(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_namespace_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_namespace( - parent='parent_value', - namespace=gcs_namespace.Namespace(name='name_value'), - namespace_id='namespace_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].namespace == gcs_namespace.Namespace(name='name_value') - assert args[0].namespace_id == 'namespace_id_value' - - -def test_create_namespace_flattened_error(): - client = RegistrationServiceClient( - 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_namespace( - registration_service.CreateNamespaceRequest(), - parent='parent_value', - namespace=gcs_namespace.Namespace(name='name_value'), - namespace_id='namespace_id_value', - ) - - -@pytest.mark.asyncio -async def test_create_namespace_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_namespace( - parent='parent_value', - namespace=gcs_namespace.Namespace(name='name_value'), - namespace_id='namespace_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].namespace == gcs_namespace.Namespace(name='name_value') - assert args[0].namespace_id == 'namespace_id_value' - - -@pytest.mark.asyncio -async def test_create_namespace_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_namespace( - registration_service.CreateNamespaceRequest(), - parent='parent_value', - namespace=gcs_namespace.Namespace(name='name_value'), - namespace_id='namespace_id_value', - ) - - -def test_list_namespaces(transport: str = 'grpc', request_type=registration_service.ListNamespacesRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespaces), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListNamespacesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_namespaces(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListNamespacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNamespacesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_namespaces_from_dict(): - test_list_namespaces(request_type=dict) - - -def test_list_namespaces_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - client.list_namespaces() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListNamespacesRequest() - - -@pytest.mark.asyncio -async def test_list_namespaces_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListNamespacesRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespaces), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_namespaces(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListNamespacesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNamespacesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_namespaces_async_from_dict(): - await test_list_namespaces_async(request_type=dict) - - -def test_list_namespaces_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListNamespacesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - call.return_value = registration_service.ListNamespacesResponse() - client.list_namespaces(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_namespaces_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListNamespacesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse()) - await client.list_namespaces(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_namespaces_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListNamespacesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_namespaces( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_namespaces_flattened_error(): - client = RegistrationServiceClient( - 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_namespaces( - registration_service.ListNamespacesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_namespaces_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListNamespacesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListNamespacesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_namespaces( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_namespaces_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_namespaces( - registration_service.ListNamespacesRequest(), - parent='parent_value', - ) - - -def test_list_namespaces_pager(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - namespace.Namespace(), - ], - next_page_token='abc', - ), - registration_service.ListNamespacesResponse( - namespaces=[], - next_page_token='def', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - ], - next_page_token='ghi', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_namespaces(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, namespace.Namespace) - for i in results) - -def test_list_namespaces_pages(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - namespace.Namespace(), - ], - next_page_token='abc', - ), - registration_service.ListNamespacesResponse( - namespaces=[], - next_page_token='def', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - ], - next_page_token='ghi', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - ], - ), - RuntimeError, - ) - pages = list(client.list_namespaces(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_namespaces_async_pager(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - namespace.Namespace(), - ], - next_page_token='abc', - ), - registration_service.ListNamespacesResponse( - namespaces=[], - next_page_token='def', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - ], - next_page_token='ghi', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_namespaces(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, namespace.Namespace) - for i in responses) - -@pytest.mark.asyncio -async def test_list_namespaces_async_pages(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_namespaces), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - namespace.Namespace(), - ], - next_page_token='abc', - ), - registration_service.ListNamespacesResponse( - namespaces=[], - next_page_token='def', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - ], - next_page_token='ghi', - ), - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_namespaces(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_namespace(transport: str = 'grpc', request_type=registration_service.GetNamespaceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = namespace.Namespace( - name='name_value', - ) - response = client.get_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, namespace.Namespace) - assert response.name == 'name_value' - - -def test_get_namespace_from_dict(): - test_get_namespace(request_type=dict) - - -def test_get_namespace_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespace), - '__call__') as call: - client.get_namespace() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetNamespaceRequest() - - -@pytest.mark.asyncio -async def test_get_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetNamespaceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace( - name='name_value', - )) - response = await client.get_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, namespace.Namespace) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_namespace_async_from_dict(): - await test_get_namespace_async(request_type=dict) - - -def test_get_namespace_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetNamespaceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespace), - '__call__') as call: - call.return_value = namespace.Namespace() - client.get_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_namespace_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetNamespaceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespace), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) - await client.get_namespace(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_namespace_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = namespace.Namespace() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_namespace( - 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] - assert args[0].name == 'name_value' - - -def test_get_namespace_flattened_error(): - client = RegistrationServiceClient( - 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_namespace( - registration_service.GetNamespaceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_namespace_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = namespace.Namespace() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_namespace( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_namespace_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_namespace( - registration_service.GetNamespaceRequest(), - name='name_value', - ) - - -def test_update_namespace(transport: str = 'grpc', request_type=registration_service.UpdateNamespaceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace( - name='name_value', - ) - response = client.update_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_namespace.Namespace) - assert response.name == 'name_value' - - -def test_update_namespace_from_dict(): - test_update_namespace(request_type=dict) - - -def test_update_namespace_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_namespace), - '__call__') as call: - client.update_namespace() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateNamespaceRequest() - - -@pytest.mark.asyncio -async def test_update_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateNamespaceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace( - name='name_value', - )) - response = await client.update_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateNamespaceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_namespace.Namespace) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_namespace_async_from_dict(): - await test_update_namespace_async(request_type=dict) - - -def test_update_namespace_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateNamespaceRequest() - - request.namespace.name = 'namespace.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_namespace), - '__call__') as call: - call.return_value = gcs_namespace.Namespace() - client.update_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'namespace.name=namespace.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_namespace_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateNamespaceRequest() - - request.namespace.name = 'namespace.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_namespace), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) - await client.update_namespace(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', - 'namespace.name=namespace.name/value', - ) in kw['metadata'] - - -def test_update_namespace_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_namespace( - namespace=gcs_namespace.Namespace(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].namespace == gcs_namespace.Namespace(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_namespace_flattened_error(): - client = RegistrationServiceClient( - 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_namespace( - registration_service.UpdateNamespaceRequest(), - namespace=gcs_namespace.Namespace(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_namespace_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_namespace.Namespace()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_namespace( - namespace=gcs_namespace.Namespace(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].namespace == gcs_namespace.Namespace(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_namespace_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_namespace( - registration_service.UpdateNamespaceRequest(), - namespace=gcs_namespace.Namespace(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_namespace(transport: str = 'grpc', request_type=registration_service.DeleteNamespaceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteNamespaceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_namespace_from_dict(): - test_delete_namespace(request_type=dict) - - -def test_delete_namespace_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_namespace), - '__call__') as call: - client.delete_namespace() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteNamespaceRequest() - - -@pytest.mark.asyncio -async def test_delete_namespace_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteNamespaceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteNamespaceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_namespace_async_from_dict(): - await test_delete_namespace_async(request_type=dict) - - -def test_delete_namespace_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteNamespaceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_namespace), - '__call__') as call: - call.return_value = None - client.delete_namespace(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_namespace_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteNamespaceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_namespace), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_namespace(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_namespace_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_namespace( - 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] - assert args[0].name == 'name_value' - - -def test_delete_namespace_flattened_error(): - client = RegistrationServiceClient( - 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_namespace( - registration_service.DeleteNamespaceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_namespace_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_namespace), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_namespace( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_namespace_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_namespace( - registration_service.DeleteNamespaceRequest(), - name='name_value', - ) - - -def test_create_service(transport: str = 'grpc', request_type=registration_service.CreateServiceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service( - name='name_value', - ) - response = client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_service.Service) - assert response.name == 'name_value' - - -def test_create_service_from_dict(): - test_create_service(request_type=dict) - - -def test_create_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - client.create_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateServiceRequest() - - -@pytest.mark.asyncio -async def test_create_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateServiceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service( - name='name_value', - )) - response = await client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_service.Service) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_service_async_from_dict(): - await test_create_service_async(request_type=dict) - - -def test_create_service_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateServiceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - call.return_value = gcs_service.Service() - client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_service_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateServiceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) - await client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_create_service_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_service( - parent='parent_value', - service=gcs_service.Service(name='name_value'), - service_id='service_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].service == gcs_service.Service(name='name_value') - assert args[0].service_id == 'service_id_value' - - -def test_create_service_flattened_error(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_service( - registration_service.CreateServiceRequest(), - parent='parent_value', - service=gcs_service.Service(name='name_value'), - service_id='service_id_value', - ) - - -@pytest.mark.asyncio -async def test_create_service_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_service( - parent='parent_value', - service=gcs_service.Service(name='name_value'), - service_id='service_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].service == gcs_service.Service(name='name_value') - assert args[0].service_id == 'service_id_value' - - -@pytest.mark.asyncio -async def test_create_service_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_service( - registration_service.CreateServiceRequest(), - parent='parent_value', - service=gcs_service.Service(name='name_value'), - service_id='service_id_value', - ) - - -def test_list_services(transport: str = 'grpc', request_type=registration_service.ListServicesRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListServicesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListServicesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_services_from_dict(): - test_list_services(request_type=dict) - - -def test_list_services_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - client.list_services() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListServicesRequest() - - -@pytest.mark.asyncio -async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListServicesRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListServicesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_services_async_from_dict(): - await test_list_services_async(request_type=dict) - - -def test_list_services_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListServicesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - call.return_value = registration_service.ListServicesResponse() - client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_services_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListServicesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse()) - await client.list_services(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_services_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListServicesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_services( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_services_flattened_error(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_services( - registration_service.ListServicesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_services_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListServicesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListServicesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_services( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_services_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_services( - registration_service.ListServicesRequest(), - parent='parent_value', - ) - - -def test_list_services_pager(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - registration_service.ListServicesResponse( - services=[], - next_page_token='def', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_services(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, service.Service) - for i in results) - -def test_list_services_pages(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - registration_service.ListServicesResponse( - services=[], - next_page_token='def', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - pages = list(client.list_services(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_services_async_pager(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - registration_service.ListServicesResponse( - services=[], - next_page_token='def', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_services(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, service.Service) - for i in responses) - -@pytest.mark.asyncio -async def test_list_services_async_pages(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - registration_service.ListServicesResponse( - services=[], - next_page_token='def', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - registration_service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_services(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_service(transport: str = 'grpc', request_type=registration_service.GetServiceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.Service( - name='name_value', - ) - response = client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == 'name_value' - - -def test_get_service_from_dict(): - test_get_service(request_type=dict) - - -def test_get_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - client.get_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetServiceRequest() - - -@pytest.mark.asyncio -async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetServiceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.Service( - name='name_value', - )) - response = await client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_service_async_from_dict(): - await test_get_service_async(request_type=dict) - - -def test_get_service_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - call.return_value = service.Service() - client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_service_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) - await client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_service_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.Service() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_service( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_service_flattened_error(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_service( - registration_service.GetServiceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_service_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.Service() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_service( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_service_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_service( - registration_service.GetServiceRequest(), - name='name_value', - ) - - -def test_update_service(transport: str = 'grpc', request_type=registration_service.UpdateServiceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service( - name='name_value', - ) - response = client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_service.Service) - assert response.name == 'name_value' - - -def test_update_service_from_dict(): - test_update_service(request_type=dict) - - -def test_update_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - client.update_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateServiceRequest() - - -@pytest.mark.asyncio -async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateServiceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service( - name='name_value', - )) - response = await client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_service.Service) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_service_async_from_dict(): - await test_update_service_async(request_type=dict) - - -def test_update_service_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateServiceRequest() - - request.service.name = 'service.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - call.return_value = gcs_service.Service() - client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service.name=service.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_service_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateServiceRequest() - - request.service.name = 'service.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) - await client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service.name=service.name/value', - ) in kw['metadata'] - - -def test_update_service_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_service( - service=gcs_service.Service(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].service == gcs_service.Service(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_service_flattened_error(): - client = RegistrationServiceClient( - 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_service( - registration_service.UpdateServiceRequest(), - service=gcs_service.Service(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_service_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_service.Service() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_service( - service=gcs_service.Service(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].service == gcs_service.Service(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_service_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_service( - registration_service.UpdateServiceRequest(), - service=gcs_service.Service(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_service(transport: str = 'grpc', request_type=registration_service.DeleteServiceRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteServiceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_service_from_dict(): - test_delete_service(request_type=dict) - - -def test_delete_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - client.delete_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteServiceRequest() - - -@pytest.mark.asyncio -async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteServiceRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteServiceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_service_async_from_dict(): - await test_delete_service_async(request_type=dict) - - -def test_delete_service_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - call.return_value = None - client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_service_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_service_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_service( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_delete_service_flattened_error(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_service( - registration_service.DeleteServiceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_service_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_service( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_service_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_service( - registration_service.DeleteServiceRequest(), - name='name_value', - ) - - -def test_create_endpoint(transport: str = 'grpc', request_type=registration_service.CreateEndpointRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - network='network_value', - ) - response = client.create_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - assert response.network == 'network_value' - - -def test_create_endpoint_from_dict(): - test_create_endpoint(request_type=dict) - - -def test_create_endpoint_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint), - '__call__') as call: - client.create_endpoint() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateEndpointRequest() - - -@pytest.mark.asyncio -async def test_create_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.CreateEndpointRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - network='network_value', - )) - response = await client.create_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.CreateEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - assert response.network == 'network_value' - - -@pytest.mark.asyncio -async def test_create_endpoint_async_from_dict(): - await test_create_endpoint_async(request_type=dict) - - -def test_create_endpoint_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateEndpointRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint), - '__call__') as call: - call.return_value = gcs_endpoint.Endpoint() - client.create_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_endpoint_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.CreateEndpointRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) - await client.create_endpoint(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_endpoint_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_endpoint( - parent='parent_value', - endpoint=gcs_endpoint.Endpoint(name='name_value'), - endpoint_id='endpoint_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') - assert args[0].endpoint_id == 'endpoint_id_value' - - -def test_create_endpoint_flattened_error(): - client = RegistrationServiceClient( - 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_endpoint( - registration_service.CreateEndpointRequest(), - parent='parent_value', - endpoint=gcs_endpoint.Endpoint(name='name_value'), - endpoint_id='endpoint_id_value', - ) - - -@pytest.mark.asyncio -async def test_create_endpoint_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_endpoint( - parent='parent_value', - endpoint=gcs_endpoint.Endpoint(name='name_value'), - endpoint_id='endpoint_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') - assert args[0].endpoint_id == 'endpoint_id_value' - - -@pytest.mark.asyncio -async def test_create_endpoint_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_endpoint( - registration_service.CreateEndpointRequest(), - parent='parent_value', - endpoint=gcs_endpoint.Endpoint(name='name_value'), - endpoint_id='endpoint_id_value', - ) - - -def test_list_endpoints(transport: str = 'grpc', request_type=registration_service.ListEndpointsRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoints), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListEndpointsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_endpoints(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListEndpointsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEndpointsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_endpoints_from_dict(): - test_list_endpoints(request_type=dict) - - -def test_list_endpoints_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - client.list_endpoints() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListEndpointsRequest() - - -@pytest.mark.asyncio -async def test_list_endpoints_async(transport: str = 'grpc_asyncio', request_type=registration_service.ListEndpointsRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoints), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_endpoints(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.ListEndpointsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEndpointsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_endpoints_async_from_dict(): - await test_list_endpoints_async(request_type=dict) - - -def test_list_endpoints_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListEndpointsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - call.return_value = registration_service.ListEndpointsResponse() - client.list_endpoints(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_endpoints_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.ListEndpointsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse()) - await client.list_endpoints(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_endpoints_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListEndpointsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_endpoints( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_endpoints_flattened_error(): - client = RegistrationServiceClient( - 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_endpoints( - registration_service.ListEndpointsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_endpoints_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListEndpointsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registration_service.ListEndpointsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_endpoints( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_endpoints_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_endpoints( - registration_service.ListEndpointsRequest(), - parent='parent_value', - ) - - -def test_list_endpoints_pager(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - next_page_token='abc', - ), - registration_service.ListEndpointsResponse( - endpoints=[], - next_page_token='def', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - ], - next_page_token='ghi', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_endpoints(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, endpoint.Endpoint) - for i in results) - -def test_list_endpoints_pages(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - next_page_token='abc', - ), - registration_service.ListEndpointsResponse( - endpoints=[], - next_page_token='def', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - ], - next_page_token='ghi', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - ), - RuntimeError, - ) - pages = list(client.list_endpoints(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_endpoints_async_pager(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - next_page_token='abc', - ), - registration_service.ListEndpointsResponse( - endpoints=[], - next_page_token='def', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - ], - next_page_token='ghi', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_endpoints(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, endpoint.Endpoint) - for i in responses) - -@pytest.mark.asyncio -async def test_list_endpoints_async_pages(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoints), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - next_page_token='abc', - ), - registration_service.ListEndpointsResponse( - endpoints=[], - next_page_token='def', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - ], - next_page_token='ghi', - ), - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_endpoints(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_endpoint(transport: str = 'grpc', request_type=registration_service.GetEndpointRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - network='network_value', - ) - response = client.get_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - assert response.network == 'network_value' - - -def test_get_endpoint_from_dict(): - test_get_endpoint(request_type=dict) - - -def test_get_endpoint_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint), - '__call__') as call: - client.get_endpoint() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetEndpointRequest() - - -@pytest.mark.asyncio -async def test_get_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.GetEndpointRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - network='network_value', - )) - response = await client.get_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.GetEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - assert response.network == 'network_value' - - -@pytest.mark.asyncio -async def test_get_endpoint_async_from_dict(): - await test_get_endpoint_async(request_type=dict) - - -def test_get_endpoint_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetEndpointRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint), - '__call__') as call: - call.return_value = endpoint.Endpoint() - client.get_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_endpoint_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.GetEndpointRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) - await client.get_endpoint(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_endpoint_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint.Endpoint() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_endpoint( - 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] - assert args[0].name == 'name_value' - - -def test_get_endpoint_flattened_error(): - client = RegistrationServiceClient( - 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_endpoint( - registration_service.GetEndpointRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_endpoint_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint.Endpoint() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_endpoint( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_endpoint_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_endpoint( - registration_service.GetEndpointRequest(), - name='name_value', - ) - - -def test_update_endpoint(transport: str = 'grpc', request_type=registration_service.UpdateEndpointRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - network='network_value', - ) - response = client.update_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - assert response.network == 'network_value' - - -def test_update_endpoint_from_dict(): - test_update_endpoint(request_type=dict) - - -def test_update_endpoint_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint), - '__call__') as call: - client.update_endpoint() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateEndpointRequest() - - -@pytest.mark.asyncio -async def test_update_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.UpdateEndpointRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint( - name='name_value', - address='address_value', - port=453, - network='network_value', - )) - response = await client.update_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.UpdateEndpointRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_endpoint.Endpoint) - assert response.name == 'name_value' - assert response.address == 'address_value' - assert response.port == 453 - assert response.network == 'network_value' - - -@pytest.mark.asyncio -async def test_update_endpoint_async_from_dict(): - await test_update_endpoint_async(request_type=dict) - - -def test_update_endpoint_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateEndpointRequest() - - request.endpoint.name = 'endpoint.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint), - '__call__') as call: - call.return_value = gcs_endpoint.Endpoint() - client.update_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'endpoint.name=endpoint.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_endpoint_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.UpdateEndpointRequest() - - request.endpoint.name = 'endpoint.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) - await client.update_endpoint(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', - 'endpoint.name=endpoint.name/value', - ) in kw['metadata'] - - -def test_update_endpoint_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_endpoint( - endpoint=gcs_endpoint.Endpoint(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_endpoint_flattened_error(): - client = RegistrationServiceClient( - 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_endpoint( - registration_service.UpdateEndpointRequest(), - endpoint=gcs_endpoint.Endpoint(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_endpoint_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_endpoint.Endpoint()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_endpoint( - endpoint=gcs_endpoint.Endpoint(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].endpoint == gcs_endpoint.Endpoint(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_endpoint_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_endpoint( - registration_service.UpdateEndpointRequest(), - endpoint=gcs_endpoint.Endpoint(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_endpoint(transport: str = 'grpc', request_type=registration_service.DeleteEndpointRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteEndpointRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_endpoint_from_dict(): - test_delete_endpoint(request_type=dict) - - -def test_delete_endpoint_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint), - '__call__') as call: - client.delete_endpoint() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteEndpointRequest() - - -@pytest.mark.asyncio -async def test_delete_endpoint_async(transport: str = 'grpc_asyncio', request_type=registration_service.DeleteEndpointRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registration_service.DeleteEndpointRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_endpoint_async_from_dict(): - await test_delete_endpoint_async(request_type=dict) - - -def test_delete_endpoint_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteEndpointRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint), - '__call__') as call: - call.return_value = None - client.delete_endpoint(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_endpoint_field_headers_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = registration_service.DeleteEndpointRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_endpoint(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_endpoint_flattened(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_endpoint( - 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] - assert args[0].name == 'name_value' - - -def test_delete_endpoint_flattened_error(): - client = RegistrationServiceClient( - 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_endpoint( - registration_service.DeleteEndpointRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_endpoint_flattened_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_endpoint( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_endpoint_flattened_error_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_endpoint( - registration_service.DeleteEndpointRequest(), - name='name_value', - ) - - -def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - test_get_iam_policy(request_type=dict) - - -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = RegistrationServiceClient( - 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() - - -def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - test_set_iam_policy(request_type=dict) - - -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = RegistrationServiceClient( - 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() - - -def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - test_test_iam_permissions(request_type=dict) - - -def test_test_iam_permissions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = RegistrationServiceClient( - 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() - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegistrationServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegistrationServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RegistrationServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RegistrationServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RegistrationServiceGrpcTransport, - transports.RegistrationServiceGrpcAsyncIOTransport, -]) -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_grpc_default(): - # A client should use the gRPC transport by default. - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RegistrationServiceGrpcTransport, - ) - -def test_registration_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RegistrationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_registration_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RegistrationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_namespace', - 'list_namespaces', - 'get_namespace', - 'update_namespace', - 'delete_namespace', - 'create_service', - 'list_services', - 'get_service', - 'update_service', - 'delete_service', - 'create_endpoint', - 'list_endpoints', - 'get_endpoint', - 'update_endpoint', - 'delete_endpoint', - 'get_iam_policy', - 'set_iam_policy', - 'test_iam_permissions', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -@requires_google_auth_gte_1_25_0 -def test_registration_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.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegistrationServiceTransport( - 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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_registration_service_base_transport_with_credentials_file_old_google_auth(): - # 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.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegistrationServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_registration_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.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegistrationServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_registration_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) - RegistrationServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_registration_service_auth_adc_old_google_auth(): - # 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) - RegistrationServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RegistrationServiceGrpcTransport, - transports.RegistrationServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_registration_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.RegistrationServiceGrpcTransport, - transports.RegistrationServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_registration_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.RegistrationServiceGrpcTransport, grpc_helpers), - (transports.RegistrationServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_registration_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( - "servicedirectory.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="servicedirectory.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) -def test_registration_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_registration_service_host_no_port(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com'), - ) - assert client.transport._host == 'servicedirectory.googleapis.com:443' - - -def test_registration_service_host_with_port(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicedirectory.googleapis.com:8000'), - ) - assert client.transport._host == 'servicedirectory.googleapis.com:8000' - -def test_registration_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegistrationServiceGrpcTransport( - 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_registration_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegistrationServiceGrpcAsyncIOTransport( - 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.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) -def test_registration_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.RegistrationServiceGrpcTransport, transports.RegistrationServiceGrpcAsyncIOTransport]) -def test_registration_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_endpoint_path(): - project = "squid" - location = "clam" - namespace = "whelk" - service = "octopus" - endpoint = "oyster" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format(project=project, location=location, namespace=namespace, service=service, endpoint=endpoint, ) - actual = RegistrationServiceClient.endpoint_path(project, location, namespace, service, endpoint) - assert expected == actual - - -def test_parse_endpoint_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "namespace": "mussel", - "service": "winkle", - "endpoint": "nautilus", - } - path = RegistrationServiceClient.endpoint_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_endpoint_path(path) - assert expected == actual - -def test_namespace_path(): - project = "scallop" - location = "abalone" - namespace = "squid" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}".format(project=project, location=location, namespace=namespace, ) - actual = RegistrationServiceClient.namespace_path(project, location, namespace) - assert expected == actual - - -def test_parse_namespace_path(): - expected = { - "project": "clam", - "location": "whelk", - "namespace": "octopus", - } - path = RegistrationServiceClient.namespace_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_namespace_path(path) - assert expected == actual - -def test_network_path(): - project = "oyster" - network = "nudibranch" - expected = "projects/{project}/locations/global/networks/{network}".format(project=project, network=network, ) - actual = RegistrationServiceClient.network_path(project, network) - assert expected == actual - - -def test_parse_network_path(): - expected = { - "project": "cuttlefish", - "network": "mussel", - } - path = RegistrationServiceClient.network_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_network_path(path) - assert expected == actual - -def test_service_path(): - project = "winkle" - location = "nautilus" - namespace = "scallop" - service = "abalone" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - actual = RegistrationServiceClient.service_path(project, location, namespace, service) - assert expected == actual - - -def test_parse_service_path(): - expected = { - "project": "squid", - "location": "clam", - "namespace": "whelk", - "service": "octopus", - } - path = RegistrationServiceClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_service_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RegistrationServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = RegistrationServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = RegistrationServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = RegistrationServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RegistrationServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = RegistrationServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = RegistrationServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = RegistrationServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.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 = RegistrationServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = RegistrationServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.RegistrationServiceTransport, '_prep_wrapped_messages') as prep: - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RegistrationServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = RegistrationServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RegistrationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = RegistrationServiceClient( - 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() diff --git a/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py b/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py index 5828bb1c..93f8333f 100644 --- a/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py +++ b/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py @@ -29,6 +29,7 @@ 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 path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.servicedirectory_v1.services.lookup_service import ( @@ -729,6 +730,9 @@ def test_lookup_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + @requires_google_auth_gte_1_25_0 def test_lookup_service_base_transport_with_credentials_file(): @@ -1245,3 +1249,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = LookupServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = LookupServiceClient( + 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() diff --git a/tests/unit/gapic/servicedirectory_v1/test_registration_service.py b/tests/unit/gapic/servicedirectory_v1/test_registration_service.py index fb22dca9..77807a8a 100644 --- a/tests/unit/gapic/servicedirectory_v1/test_registration_service.py +++ b/tests/unit/gapic/servicedirectory_v1/test_registration_service.py @@ -29,6 +29,7 @@ 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 path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.servicedirectory_v1.services.registration_service import ( @@ -4786,6 +4787,9 @@ def test_registration_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + @requires_google_auth_gte_1_25_0 def test_registration_service_base_transport_with_credentials_file(): @@ -5332,3 +5336,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = RegistrationServiceClient( + 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() diff --git a/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py b/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py index 5bf786eb..e3ade2d0 100644 --- a/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py +++ b/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py @@ -29,6 +29,7 @@ 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 path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.servicedirectory_v1beta1.services.lookup_service import ( @@ -731,6 +732,9 @@ def test_lookup_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + @requires_google_auth_gte_1_25_0 def test_lookup_service_base_transport_with_credentials_file(): @@ -1269,3 +1273,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = LookupServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = LookupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = LookupServiceClient( + 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() diff --git a/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py b/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py index 048d031a..b26c4798 100644 --- a/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py +++ b/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py @@ -29,6 +29,7 @@ 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 path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.servicedirectory_v1beta1.services.registration_service import ( @@ -4819,6 +4820,9 @@ def test_registration_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + @requires_google_auth_gte_1_25_0 def test_registration_service_base_transport_with_credentials_file(): @@ -5387,3 +5391,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RegistrationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = RegistrationServiceClient( + 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()