From 004e30366208135198b13c6383242ec85c825f41 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 11 Apr 2022 22:53:42 +0000 Subject: [PATCH 1/3] chore: Use gapic-generator-python 0.65.0 PiperOrigin-RevId: 440970084 Source-Link: https://github.com/googleapis/googleapis/commit/5e0a3d57254ab9857ccac77fc6ffade7b69a2dc7 Source-Link: https://github.com/googleapis/googleapis-gen/commit/b0c628a3fade768f225d76992791ea1ba2a881be Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjBjNjI4YTNmYWRlNzY4ZjIyNWQ3Njk5Mjc5MWVhMWJhMmE4ODFiZSJ9 --- owl-bot-staging/v2/.coveragerc | 17 + owl-bot-staging/v2/.flake8 | 33 + owl-bot-staging/v2/MANIFEST.in | 2 + owl-bot-staging/v2/README.rst | 49 + owl-bot-staging/v2/docs/conf.py | 376 ++ owl-bot-staging/v2/docs/index.rst | 7 + owl-bot-staging/v2/docs/run_v2/revisions.rst | 10 + owl-bot-staging/v2/docs/run_v2/services.rst | 7 + owl-bot-staging/v2/docs/run_v2/types.rst | 7 + .../v2/google/cloud/run/__init__.py | 93 + owl-bot-staging/v2/google/cloud/run/py.typed | 2 + .../v2/google/cloud/run_v2/__init__.py | 94 + .../google/cloud/run_v2/gapic_metadata.json | 147 + .../v2/google/cloud/run_v2/py.typed | 2 + .../google/cloud/run_v2/services/__init__.py | 15 + .../run_v2/services/revisions/__init__.py | 22 + .../run_v2/services/revisions/async_client.py | 543 +++ .../cloud/run_v2/services/revisions/client.py | 787 ++++ .../cloud/run_v2/services/revisions/pagers.py | 139 + .../services/revisions/transports/__init__.py | 33 + .../services/revisions/transports/base.py | 185 + .../services/revisions/transports/grpc.py | 334 ++ .../revisions/transports/grpc_asyncio.py | 333 ++ .../run_v2/services/services/__init__.py | 22 + .../run_v2/services/services/async_client.py | 1176 ++++++ .../cloud/run_v2/services/services/client.py | 1405 +++++++ .../cloud/run_v2/services/services/pagers.py | 139 + .../services/services/transports/__init__.py | 33 + .../services/services/transports/base.py | 270 ++ .../services/services/transports/grpc.py | 475 +++ .../services/transports/grpc_asyncio.py | 474 +++ .../v2/google/cloud/run_v2/types/__init__.py | 98 + .../v2/google/cloud/run_v2/types/condition.py | 214 ++ .../v2/google/cloud/run_v2/types/k8s_min.py | 477 +++ .../v2/google/cloud/run_v2/types/revision.py | 388 ++ .../cloud/run_v2/types/revision_template.py | 145 + .../v2/google/cloud/run_v2/types/service.py | 521 +++ .../cloud/run_v2/types/traffic_target.py | 115 + .../cloud/run_v2/types/vendor_settings.py | 131 + owl-bot-staging/v2/mypy.ini | 3 + owl-bot-staging/v2/noxfile.py | 180 + ...nerated_revisions_delete_revision_async.py | 49 + ...enerated_revisions_delete_revision_sync.py | 49 + ..._generated_revisions_get_revision_async.py | 45 + ...2_generated_revisions_get_revision_sync.py | 45 + ...enerated_revisions_list_revisions_async.py | 46 + ...generated_revisions_list_revisions_sync.py | 46 + ...generated_services_create_service_async.py | 50 + ..._generated_services_create_service_sync.py | 50 + ...generated_services_delete_service_async.py | 49 + ..._generated_services_delete_service_sync.py | 49 + ...generated_services_get_iam_policy_async.py | 45 + ..._generated_services_get_iam_policy_sync.py | 45 + ...v2_generated_services_get_service_async.py | 45 + ..._v2_generated_services_get_service_sync.py | 45 + ..._generated_services_list_services_async.py | 46 + ...2_generated_services_list_services_sync.py | 46 + ...generated_services_set_iam_policy_async.py | 45 + ..._generated_services_set_iam_policy_sync.py | 45 + ...ted_services_test_iam_permissions_async.py | 46 + ...ated_services_test_iam_permissions_sync.py | 46 + ...generated_services_update_service_async.py | 48 + ..._generated_services_update_service_sync.py | 48 + .../snippet_metadata_run_v2.json | 983 +++++ .../v2/scripts/fixup_run_v2_keywords.py | 186 + owl-bot-staging/v2/setup.py | 60 + owl-bot-staging/v2/tests/__init__.py | 16 + owl-bot-staging/v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../v2/tests/unit/gapic/run_v2/__init__.py | 16 + .../tests/unit/gapic/run_v2/test_revisions.py | 2197 +++++++++++ .../tests/unit/gapic/run_v2/test_services.py | 3218 +++++++++++++++++ 72 files changed, 17239 insertions(+) create mode 100644 owl-bot-staging/v2/.coveragerc create mode 100644 owl-bot-staging/v2/.flake8 create mode 100644 owl-bot-staging/v2/MANIFEST.in create mode 100644 owl-bot-staging/v2/README.rst create mode 100644 owl-bot-staging/v2/docs/conf.py create mode 100644 owl-bot-staging/v2/docs/index.rst create mode 100644 owl-bot-staging/v2/docs/run_v2/revisions.rst create mode 100644 owl-bot-staging/v2/docs/run_v2/services.rst create mode 100644 owl-bot-staging/v2/docs/run_v2/types.rst create mode 100644 owl-bot-staging/v2/google/cloud/run/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/run/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/gapic_metadata.json create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/client.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/client.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/condition.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/k8s_min.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/revision.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/revision_template.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/service.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/traffic_target.py create mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/vendor_settings.py create mode 100644 owl-bot-staging/v2/mypy.ini create mode 100644 owl-bot-staging/v2/noxfile.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_run_v2.json create mode 100644 owl-bot-staging/v2/scripts/fixup_run_v2_keywords.py create mode 100644 owl-bot-staging/v2/setup.py create mode 100644 owl-bot-staging/v2/tests/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/run_v2/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/run_v2/test_revisions.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/run_v2/test_services.py diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc new file mode 100644 index 0000000..03a3142 --- /dev/null +++ b/owl-bot-staging/v2/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/run/__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/v2/.flake8 b/owl-bot-staging/v2/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in new file mode 100644 index 0000000..fb6bb81 --- /dev/null +++ b/owl-bot-staging/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/run *.py +recursive-include google/cloud/run_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst new file mode 100644 index 0000000..ca52f66 --- /dev/null +++ b/owl-bot-staging/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Run 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 Run 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/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py new file mode 100644 index 0000000..f4aa161 --- /dev/null +++ b/owl-bot-staging/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-run documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-run" +copyright = u"2022, 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-run-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-run.tex", + u"google-cloud-run Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-run", + u"Google Cloud Run Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-run", + u"google-cloud-run Documentation", + author, + "google-cloud-run", + "GAPIC library for Google Cloud Run 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/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst new file mode 100644 index 0000000..da0a990 --- /dev/null +++ b/owl-bot-staging/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + run_v2/services + run_v2/types diff --git a/owl-bot-staging/v2/docs/run_v2/revisions.rst b/owl-bot-staging/v2/docs/run_v2/revisions.rst new file mode 100644 index 0000000..e4b2219 --- /dev/null +++ b/owl-bot-staging/v2/docs/run_v2/revisions.rst @@ -0,0 +1,10 @@ +Revisions +--------------------------- + +.. automodule:: google.cloud.run_v2.services.revisions + :members: + :inherited-members: + +.. automodule:: google.cloud.run_v2.services.revisions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/run_v2/services.rst b/owl-bot-staging/v2/docs/run_v2/services.rst new file mode 100644 index 0000000..533d18a --- /dev/null +++ b/owl-bot-staging/v2/docs/run_v2/services.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Run v2 API +==================================== +.. toctree:: + :maxdepth: 2 + + revisions + services diff --git a/owl-bot-staging/v2/docs/run_v2/types.rst b/owl-bot-staging/v2/docs/run_v2/types.rst new file mode 100644 index 0000000..a45661d --- /dev/null +++ b/owl-bot-staging/v2/docs/run_v2/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Run v2 API +================================= + +.. automodule:: google.cloud.run_v2.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2/google/cloud/run/__init__.py b/owl-bot-staging/v2/google/cloud/run/__init__.py new file mode 100644 index 0000000..48668d4 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run/__init__.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.run_v2.services.revisions.client import RevisionsClient +from google.cloud.run_v2.services.revisions.async_client import RevisionsAsyncClient +from google.cloud.run_v2.services.services.client import ServicesClient +from google.cloud.run_v2.services.services.async_client import ServicesAsyncClient + +from google.cloud.run_v2.types.condition import Condition +from google.cloud.run_v2.types.k8s_min import CloudSqlInstance +from google.cloud.run_v2.types.k8s_min import Container +from google.cloud.run_v2.types.k8s_min import ContainerPort +from google.cloud.run_v2.types.k8s_min import EnvVar +from google.cloud.run_v2.types.k8s_min import EnvVarSource +from google.cloud.run_v2.types.k8s_min import ResourceRequirements +from google.cloud.run_v2.types.k8s_min import SecretKeySelector +from google.cloud.run_v2.types.k8s_min import SecretVolumeSource +from google.cloud.run_v2.types.k8s_min import VersionToPath +from google.cloud.run_v2.types.k8s_min import Volume +from google.cloud.run_v2.types.k8s_min import VolumeMount +from google.cloud.run_v2.types.revision import DeleteRevisionRequest +from google.cloud.run_v2.types.revision import GetRevisionRequest +from google.cloud.run_v2.types.revision import ListRevisionsRequest +from google.cloud.run_v2.types.revision import ListRevisionsResponse +from google.cloud.run_v2.types.revision import Revision +from google.cloud.run_v2.types.revision_template import RevisionTemplate +from google.cloud.run_v2.types.service import CreateServiceRequest +from google.cloud.run_v2.types.service import DeleteServiceRequest +from google.cloud.run_v2.types.service import GetServiceRequest +from google.cloud.run_v2.types.service import ListServicesRequest +from google.cloud.run_v2.types.service import ListServicesResponse +from google.cloud.run_v2.types.service import Service +from google.cloud.run_v2.types.service import UpdateServiceRequest +from google.cloud.run_v2.types.traffic_target import TrafficTarget +from google.cloud.run_v2.types.traffic_target import TrafficTargetStatus +from google.cloud.run_v2.types.traffic_target import TrafficTargetAllocationType +from google.cloud.run_v2.types.vendor_settings import BinaryAuthorization +from google.cloud.run_v2.types.vendor_settings import RevisionScaling +from google.cloud.run_v2.types.vendor_settings import VpcAccess +from google.cloud.run_v2.types.vendor_settings import ExecutionEnvironment +from google.cloud.run_v2.types.vendor_settings import IngressTraffic + +__all__ = ('RevisionsClient', + 'RevisionsAsyncClient', + 'ServicesClient', + 'ServicesAsyncClient', + 'Condition', + 'CloudSqlInstance', + 'Container', + 'ContainerPort', + 'EnvVar', + 'EnvVarSource', + 'ResourceRequirements', + 'SecretKeySelector', + 'SecretVolumeSource', + 'VersionToPath', + 'Volume', + 'VolumeMount', + 'DeleteRevisionRequest', + 'GetRevisionRequest', + 'ListRevisionsRequest', + 'ListRevisionsResponse', + 'Revision', + 'RevisionTemplate', + 'CreateServiceRequest', + 'DeleteServiceRequest', + 'GetServiceRequest', + 'ListServicesRequest', + 'ListServicesResponse', + 'Service', + 'UpdateServiceRequest', + 'TrafficTarget', + 'TrafficTargetStatus', + 'TrafficTargetAllocationType', + 'BinaryAuthorization', + 'RevisionScaling', + 'VpcAccess', + 'ExecutionEnvironment', + 'IngressTraffic', +) diff --git a/owl-bot-staging/v2/google/cloud/run/py.typed b/owl-bot-staging/v2/google/cloud/run/py.typed new file mode 100644 index 0000000..a94ba23 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-run package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/run_v2/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/__init__.py new file mode 100644 index 0000000..8ba23e1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/__init__.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.revisions import RevisionsClient +from .services.revisions import RevisionsAsyncClient +from .services.services import ServicesClient +from .services.services import ServicesAsyncClient + +from .types.condition import Condition +from .types.k8s_min import CloudSqlInstance +from .types.k8s_min import Container +from .types.k8s_min import ContainerPort +from .types.k8s_min import EnvVar +from .types.k8s_min import EnvVarSource +from .types.k8s_min import ResourceRequirements +from .types.k8s_min import SecretKeySelector +from .types.k8s_min import SecretVolumeSource +from .types.k8s_min import VersionToPath +from .types.k8s_min import Volume +from .types.k8s_min import VolumeMount +from .types.revision import DeleteRevisionRequest +from .types.revision import GetRevisionRequest +from .types.revision import ListRevisionsRequest +from .types.revision import ListRevisionsResponse +from .types.revision import Revision +from .types.revision_template import RevisionTemplate +from .types.service import CreateServiceRequest +from .types.service import DeleteServiceRequest +from .types.service import GetServiceRequest +from .types.service import ListServicesRequest +from .types.service import ListServicesResponse +from .types.service import Service +from .types.service import UpdateServiceRequest +from .types.traffic_target import TrafficTarget +from .types.traffic_target import TrafficTargetStatus +from .types.traffic_target import TrafficTargetAllocationType +from .types.vendor_settings import BinaryAuthorization +from .types.vendor_settings import RevisionScaling +from .types.vendor_settings import VpcAccess +from .types.vendor_settings import ExecutionEnvironment +from .types.vendor_settings import IngressTraffic + +__all__ = ( + 'RevisionsAsyncClient', + 'ServicesAsyncClient', +'BinaryAuthorization', +'CloudSqlInstance', +'Condition', +'Container', +'ContainerPort', +'CreateServiceRequest', +'DeleteRevisionRequest', +'DeleteServiceRequest', +'EnvVar', +'EnvVarSource', +'ExecutionEnvironment', +'GetRevisionRequest', +'GetServiceRequest', +'IngressTraffic', +'ListRevisionsRequest', +'ListRevisionsResponse', +'ListServicesRequest', +'ListServicesResponse', +'ResourceRequirements', +'Revision', +'RevisionScaling', +'RevisionTemplate', +'RevisionsClient', +'SecretKeySelector', +'SecretVolumeSource', +'Service', +'ServicesClient', +'TrafficTarget', +'TrafficTargetAllocationType', +'TrafficTargetStatus', +'UpdateServiceRequest', +'VersionToPath', +'Volume', +'VolumeMount', +'VpcAccess', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/run_v2/gapic_metadata.json new file mode 100644 index 0000000..995df8c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/gapic_metadata.json @@ -0,0 +1,147 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.run_v2", + "protoPackage": "google.cloud.run.v2", + "schema": "1.0", + "services": { + "Revisions": { + "clients": { + "grpc": { + "libraryClient": "RevisionsClient", + "rpcs": { + "DeleteRevision": { + "methods": [ + "delete_revision" + ] + }, + "GetRevision": { + "methods": [ + "get_revision" + ] + }, + "ListRevisions": { + "methods": [ + "list_revisions" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RevisionsAsyncClient", + "rpcs": { + "DeleteRevision": { + "methods": [ + "delete_revision" + ] + }, + "GetRevision": { + "methods": [ + "get_revision" + ] + }, + "ListRevisions": { + "methods": [ + "list_revisions" + ] + } + } + } + } + }, + "Services": { + "clients": { + "grpc": { + "libraryClient": "ServicesClient", + "rpcs": { + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServicesAsyncClient", + "rpcs": { + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2/google/cloud/run_v2/py.typed b/owl-bot-staging/v2/google/cloud/run_v2/py.typed new file mode 100644 index 0000000..a94ba23 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-run package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v2/google/cloud/run_v2/services/revisions/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/__init__.py new file mode 100644 index 0000000..1ffa1d4 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 RevisionsClient +from .async_client import RevisionsAsyncClient + +__all__ = ( + 'RevisionsClient', + 'RevisionsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/async_client.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/async_client.py new file mode 100644 index 0000000..4264b3d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/async_client.py @@ -0,0 +1,543 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.run_v2.services.revisions import pagers +from google.cloud.run_v2.types import condition +from google.cloud.run_v2.types import k8s_min +from google.cloud.run_v2.types import revision +from google.cloud.run_v2.types import vendor_settings +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import RevisionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RevisionsGrpcAsyncIOTransport +from .client import RevisionsClient + + +class RevisionsAsyncClient: + """Cloud Run Revision Control Plane API.""" + + _client: RevisionsClient + + DEFAULT_ENDPOINT = RevisionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RevisionsClient.DEFAULT_MTLS_ENDPOINT + + connector_path = staticmethod(RevisionsClient.connector_path) + parse_connector_path = staticmethod(RevisionsClient.parse_connector_path) + crypto_key_path = staticmethod(RevisionsClient.crypto_key_path) + parse_crypto_key_path = staticmethod(RevisionsClient.parse_crypto_key_path) + revision_path = staticmethod(RevisionsClient.revision_path) + parse_revision_path = staticmethod(RevisionsClient.parse_revision_path) + secret_path = staticmethod(RevisionsClient.secret_path) + parse_secret_path = staticmethod(RevisionsClient.parse_secret_path) + secret_version_path = staticmethod(RevisionsClient.secret_version_path) + parse_secret_version_path = staticmethod(RevisionsClient.parse_secret_version_path) + service_path = staticmethod(RevisionsClient.service_path) + parse_service_path = staticmethod(RevisionsClient.parse_service_path) + common_billing_account_path = staticmethod(RevisionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RevisionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RevisionsClient.common_folder_path) + parse_common_folder_path = staticmethod(RevisionsClient.parse_common_folder_path) + common_organization_path = staticmethod(RevisionsClient.common_organization_path) + parse_common_organization_path = staticmethod(RevisionsClient.parse_common_organization_path) + common_project_path = staticmethod(RevisionsClient.common_project_path) + parse_common_project_path = staticmethod(RevisionsClient.parse_common_project_path) + common_location_path = staticmethod(RevisionsClient.common_location_path) + parse_common_location_path = staticmethod(RevisionsClient.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: + RevisionsAsyncClient: The constructed client. + """ + return RevisionsClient.from_service_account_info.__func__(RevisionsAsyncClient, 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: + RevisionsAsyncClient: The constructed client. + """ + return RevisionsClient.from_service_account_file.__func__(RevisionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RevisionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RevisionsTransport: + """Returns the transport used by the client instance. + + Returns: + RevisionsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RevisionsClient).get_transport_class, type(RevisionsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, RevisionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the revisions 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, ~.RevisionsTransport]): 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 = RevisionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_revision(self, + request: Union[revision.GetRevisionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> revision.Revision: + r"""Gets information about a Revision. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_get_revision(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.GetRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.GetRevisionRequest, dict]): + The request object. Request message for obtaining a + Revision by its full name. + name (:class:`str`): + Required. The full name of the + Revision. Format: + projects/{project}/locations/{location}/services/{service}/revisions/{revision} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.run_v2.types.Revision: + A Revision is an immutable snapshot + of code and configuration. A Revision + references a container image. Revisions + are only created by updates to its + parent Service. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = revision.GetRevisionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_revision, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_revisions(self, + request: Union[revision.ListRevisionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListRevisionsAsyncPager: + r"""List Revisions from a given Service, or from a given + location. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_list_revisions(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.ListRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.run_v2.types.ListRevisionsRequest, dict]): + The request object. Request message for retrieving a + list of Revisions. + parent (:class:`str`): + Required. The Service from which the + Revisions should be listed. To list all + Revisions across Services, use "-" + instead of Service name. Format: + projects/{project}/locations/{location}/services/{service} + + 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.run_v2.services.revisions.pagers.ListRevisionsAsyncPager: + Response message containing a list of + Revisions. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = revision.ListRevisionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_revisions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRevisionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_revision(self, + request: Union[revision.DeleteRevisionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a Revision. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_delete_revision(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.DeleteRevisionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_revision(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.DeleteRevisionRequest, dict]): + The request object. Request message for deleting a + retired Revision. Revision lifecycle is usually managed + by making changes to the parent Service. Only retired + revisions can be deleted with this API. + name (:class:`str`): + Required. The name of the Revision to + delete. Format: + projects/{project}/locations/{location}/services/{service}/revisions/{revision} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Revision` A Revision is an immutable snapshot of code and configuration. A Revision + references a container image. Revisions are only + created by updates to its parent Service. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = revision.DeleteRevisionRequest(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_revision, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + revision.Revision, + metadata_type=revision.Revision, + ) + + # 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-run", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "RevisionsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/client.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/client.py new file mode 100644 index 0000000..8aeda60 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/client.py @@ -0,0 +1,787 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.run_v2.services.revisions import pagers +from google.cloud.run_v2.types import condition +from google.cloud.run_v2.types import k8s_min +from google.cloud.run_v2.types import revision +from google.cloud.run_v2.types import vendor_settings +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import RevisionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RevisionsGrpcTransport +from .transports.grpc_asyncio import RevisionsGrpcAsyncIOTransport + + +class RevisionsClientMeta(type): + """Metaclass for the Revisions 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[RevisionsTransport]] + _transport_registry["grpc"] = RevisionsGrpcTransport + _transport_registry["grpc_asyncio"] = RevisionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[RevisionsTransport]: + """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 RevisionsClient(metaclass=RevisionsClientMeta): + """Cloud Run Revision Control Plane API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "run.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: + RevisionsClient: 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: + RevisionsClient: 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) -> RevisionsTransport: + """Returns the transport used by the client instance. + + Returns: + RevisionsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def connector_path(project: str,location: str,connector: str,) -> str: + """Returns a fully-qualified connector string.""" + return "projects/{project}/locations/{location}/connectors/{connector}".format(project=project, location=location, connector=connector, ) + + @staticmethod + def parse_connector_path(path: str) -> Dict[str,str]: + """Parses a connector path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/connectors/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str,str]: + """Parses a crypto_key path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def revision_path(project: str,location: str,service: str,revision: str,) -> str: + """Returns a fully-qualified revision string.""" + return "projects/{project}/locations/{location}/services/{service}/revisions/{revision}".format(project=project, location=location, service=service, revision=revision, ) + + @staticmethod + def parse_revision_path(path: str) -> Dict[str,str]: + """Parses a revision path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)/revisions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def secret_path(project: str,secret: str,) -> str: + """Returns a fully-qualified secret string.""" + return "projects/{project}/secrets/{secret}".format(project=project, secret=secret, ) + + @staticmethod + def parse_secret_path(path: str) -> Dict[str,str]: + """Parses a secret path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def secret_version_path(project: str,secret: str,version: str,) -> str: + """Returns a fully-qualified secret_version string.""" + return "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) + + @staticmethod + def parse_secret_version_path(path: str) -> Dict[str,str]: + """Parses a secret_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, 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.+?)/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 {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RevisionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the revisions 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, RevisionsTransport]): 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() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RevisionsTransport): + # transport is a RevisionsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def get_revision(self, + request: Union[revision.GetRevisionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> revision.Revision: + r"""Gets information about a Revision. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_get_revision(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.GetRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.GetRevisionRequest, dict]): + The request object. Request message for obtaining a + Revision by its full name. + name (str): + Required. The full name of the + Revision. Format: + projects/{project}/locations/{location}/services/{service}/revisions/{revision} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.run_v2.types.Revision: + A Revision is an immutable snapshot + of code and configuration. A Revision + references a container image. Revisions + are only created by updates to its + parent Service. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a revision.GetRevisionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, revision.GetRevisionRequest): + request = revision.GetRevisionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_revision] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_revisions(self, + request: Union[revision.ListRevisionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListRevisionsPager: + r"""List Revisions from a given Service, or from a given + location. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_list_revisions(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.ListRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.run_v2.types.ListRevisionsRequest, dict]): + The request object. Request message for retrieving a + list of Revisions. + parent (str): + Required. The Service from which the + Revisions should be listed. To list all + Revisions across Services, use "-" + instead of Service name. Format: + projects/{project}/locations/{location}/services/{service} + + 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.run_v2.services.revisions.pagers.ListRevisionsPager: + Response message containing a list of + Revisions. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a revision.ListRevisionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, revision.ListRevisionsRequest): + request = revision.ListRevisionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_revisions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRevisionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_revision(self, + request: Union[revision.DeleteRevisionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a Revision. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_delete_revision(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.DeleteRevisionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_revision(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.DeleteRevisionRequest, dict]): + The request object. Request message for deleting a + retired Revision. Revision lifecycle is usually managed + by making changes to the parent Service. Only retired + revisions can be deleted with this API. + name (str): + Required. The name of the Revision to + delete. Format: + projects/{project}/locations/{location}/services/{service}/revisions/{revision} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Revision` A Revision is an immutable snapshot of code and configuration. A Revision + references a container image. Revisions are only + created by updates to its parent Service. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a revision.DeleteRevisionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, revision.DeleteRevisionRequest): + request = revision.DeleteRevisionRequest(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_revision] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + revision.Revision, + metadata_type=revision.Revision, + ) + + # 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-run", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "RevisionsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/pagers.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/pagers.py new file mode 100644 index 0000000..9027d58 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.run_v2.types import revision + + +class ListRevisionsPager: + """A pager for iterating through ``list_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.run_v2.types.ListRevisionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``revisions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRevisions`` requests and continue to iterate + through the ``revisions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.run_v2.types.ListRevisionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., revision.ListRevisionsResponse], + request: revision.ListRevisionsRequest, + response: revision.ListRevisionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.run_v2.types.ListRevisionsRequest): + The initial request object. + response (google.cloud.run_v2.types.ListRevisionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = revision.ListRevisionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[revision.ListRevisionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[revision.Revision]: + for page in self.pages: + yield from page.revisions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRevisionsAsyncPager: + """A pager for iterating through ``list_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.run_v2.types.ListRevisionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``revisions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRevisions`` requests and continue to iterate + through the ``revisions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.run_v2.types.ListRevisionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[revision.ListRevisionsResponse]], + request: revision.ListRevisionsRequest, + response: revision.ListRevisionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.run_v2.types.ListRevisionsRequest): + The initial request object. + response (google.cloud.run_v2.types.ListRevisionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = revision.ListRevisionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[revision.ListRevisionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[revision.Revision]: + async def async_generator(): + async for page in self.pages: + for response in page.revisions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/__init__.py new file mode 100644 index 0000000..2153a3a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 RevisionsTransport +from .grpc import RevisionsGrpcTransport +from .grpc_asyncio import RevisionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RevisionsTransport]] +_transport_registry['grpc'] = RevisionsGrpcTransport +_transport_registry['grpc_asyncio'] = RevisionsGrpcAsyncIOTransport + +__all__ = ( + 'RevisionsTransport', + 'RevisionsGrpcTransport', + 'RevisionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/base.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/base.py new file mode 100644 index 0000000..9dfa562 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/base.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.run_v2.types import revision +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-run', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class RevisionsTransport(abc.ABC): + """Abstract transport class for Revisions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'run.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_revision: gapic_v1.method.wrap_method( + self.get_revision, + default_timeout=None, + client_info=client_info, + ), + self.list_revisions: gapic_v1.method.wrap_method( + self.list_revisions, + default_timeout=None, + client_info=client_info, + ), + self.delete_revision: gapic_v1.method.wrap_method( + self.delete_revision, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_revision(self) -> Callable[ + [revision.GetRevisionRequest], + Union[ + revision.Revision, + Awaitable[revision.Revision] + ]]: + raise NotImplementedError() + + @property + def list_revisions(self) -> Callable[ + [revision.ListRevisionsRequest], + Union[ + revision.ListRevisionsResponse, + Awaitable[revision.ListRevisionsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_revision(self) -> Callable[ + [revision.DeleteRevisionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RevisionsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc.py new file mode 100644 index 0000000..6aeada1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc.py @@ -0,0 +1,334 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.run_v2.types import revision +from google.longrunning import operations_pb2 # type: ignore +from .base import RevisionsTransport, DEFAULT_CLIENT_INFO + + +class RevisionsGrpcTransport(RevisionsTransport): + """gRPC backend transport for Revisions. + + Cloud Run Revision Control Plane API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'run.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'run.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_revision(self) -> Callable[ + [revision.GetRevisionRequest], + revision.Revision]: + r"""Return a callable for the get revision method over gRPC. + + Gets information about a Revision. + + Returns: + Callable[[~.GetRevisionRequest], + ~.Revision]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_revision' not in self._stubs: + self._stubs['get_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Revisions/GetRevision', + request_serializer=revision.GetRevisionRequest.serialize, + response_deserializer=revision.Revision.deserialize, + ) + return self._stubs['get_revision'] + + @property + def list_revisions(self) -> Callable[ + [revision.ListRevisionsRequest], + revision.ListRevisionsResponse]: + r"""Return a callable for the list revisions method over gRPC. + + List Revisions from a given Service, or from a given + location. + + Returns: + Callable[[~.ListRevisionsRequest], + ~.ListRevisionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_revisions' not in self._stubs: + self._stubs['list_revisions'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Revisions/ListRevisions', + request_serializer=revision.ListRevisionsRequest.serialize, + response_deserializer=revision.ListRevisionsResponse.deserialize, + ) + return self._stubs['list_revisions'] + + @property + def delete_revision(self) -> Callable[ + [revision.DeleteRevisionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete revision method over gRPC. + + Delete a Revision. + + Returns: + Callable[[~.DeleteRevisionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_revision' not in self._stubs: + self._stubs['delete_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Revisions/DeleteRevision', + request_serializer=revision.DeleteRevisionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_revision'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RevisionsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py new file mode 100644 index 0000000..15dd3ef --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py @@ -0,0 +1,333 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.run_v2.types import revision +from google.longrunning import operations_pb2 # type: ignore +from .base import RevisionsTransport, DEFAULT_CLIENT_INFO +from .grpc import RevisionsGrpcTransport + + +class RevisionsGrpcAsyncIOTransport(RevisionsTransport): + """gRPC AsyncIO backend transport for Revisions. + + Cloud Run Revision Control Plane API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'run.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 = 'run.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_revision(self) -> Callable[ + [revision.GetRevisionRequest], + Awaitable[revision.Revision]]: + r"""Return a callable for the get revision method over gRPC. + + Gets information about a Revision. + + Returns: + Callable[[~.GetRevisionRequest], + Awaitable[~.Revision]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_revision' not in self._stubs: + self._stubs['get_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Revisions/GetRevision', + request_serializer=revision.GetRevisionRequest.serialize, + response_deserializer=revision.Revision.deserialize, + ) + return self._stubs['get_revision'] + + @property + def list_revisions(self) -> Callable[ + [revision.ListRevisionsRequest], + Awaitable[revision.ListRevisionsResponse]]: + r"""Return a callable for the list revisions method over gRPC. + + List Revisions from a given Service, or from a given + location. + + Returns: + Callable[[~.ListRevisionsRequest], + Awaitable[~.ListRevisionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_revisions' not in self._stubs: + self._stubs['list_revisions'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Revisions/ListRevisions', + request_serializer=revision.ListRevisionsRequest.serialize, + response_deserializer=revision.ListRevisionsResponse.deserialize, + ) + return self._stubs['list_revisions'] + + @property + def delete_revision(self) -> Callable[ + [revision.DeleteRevisionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete revision method over gRPC. + + Delete a Revision. + + Returns: + Callable[[~.DeleteRevisionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_revision' not in self._stubs: + self._stubs['delete_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Revisions/DeleteRevision', + request_serializer=revision.DeleteRevisionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_revision'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'RevisionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/__init__.py new file mode 100644 index 0000000..531e71a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/services/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ServicesClient +from .async_client import ServicesAsyncClient + +__all__ = ( + 'ServicesClient', + 'ServicesAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/async_client.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/async_client.py new file mode 100644 index 0000000..bfbdd35 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/services/async_client.py @@ -0,0 +1,1176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.run_v2.services.services import pagers +from google.cloud.run_v2.types import condition +from google.cloud.run_v2.types import revision_template +from google.cloud.run_v2.types import service +from google.cloud.run_v2.types import service as gcr_service +from google.cloud.run_v2.types import traffic_target +from google.cloud.run_v2.types import vendor_settings +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 ServicesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport +from .client import ServicesClient + + +class ServicesAsyncClient: + """Cloud Run Service Control Plane API""" + + _client: ServicesClient + + DEFAULT_ENDPOINT = ServicesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ServicesClient.DEFAULT_MTLS_ENDPOINT + + connector_path = staticmethod(ServicesClient.connector_path) + parse_connector_path = staticmethod(ServicesClient.parse_connector_path) + crypto_key_path = staticmethod(ServicesClient.crypto_key_path) + parse_crypto_key_path = staticmethod(ServicesClient.parse_crypto_key_path) + revision_path = staticmethod(ServicesClient.revision_path) + parse_revision_path = staticmethod(ServicesClient.parse_revision_path) + secret_path = staticmethod(ServicesClient.secret_path) + parse_secret_path = staticmethod(ServicesClient.parse_secret_path) + secret_version_path = staticmethod(ServicesClient.secret_version_path) + parse_secret_version_path = staticmethod(ServicesClient.parse_secret_version_path) + service_path = staticmethod(ServicesClient.service_path) + parse_service_path = staticmethod(ServicesClient.parse_service_path) + common_billing_account_path = staticmethod(ServicesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ServicesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ServicesClient.common_folder_path) + parse_common_folder_path = staticmethod(ServicesClient.parse_common_folder_path) + common_organization_path = staticmethod(ServicesClient.common_organization_path) + parse_common_organization_path = staticmethod(ServicesClient.parse_common_organization_path) + common_project_path = staticmethod(ServicesClient.common_project_path) + parse_common_project_path = staticmethod(ServicesClient.parse_common_project_path) + common_location_path = staticmethod(ServicesClient.common_location_path) + parse_common_location_path = staticmethod(ServicesClient.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: + ServicesAsyncClient: The constructed client. + """ + return ServicesClient.from_service_account_info.__func__(ServicesAsyncClient, 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: + ServicesAsyncClient: The constructed client. + """ + return ServicesClient.from_service_account_file.__func__(ServicesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ServicesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ServicesTransport: + """Returns the transport used by the client instance. + + Returns: + ServicesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ServicesClient).get_transport_class, type(ServicesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ServicesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the services 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, ~.ServicesTransport]): 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 = ServicesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_service(self, + request: Union[gcr_service.CreateServiceRequest, dict] = None, + *, + parent: str = None, + service: gcr_service.Service = None, + service_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Service in a given project and + location. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_create_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.CreateServiceRequest, dict]): + The request object. Request message for creating a + Service. + parent (:class:`str`): + Required. The location and project in + which this service should be created. + Format: + projects/{projectnumber}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (:class:`google.cloud.run_v2.types.Service`): + Required. The Service instance to + create. + + 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 unique identifier for the Service. The + name of the service becomes + {parent}/services/{service_id}. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of + configurations and revision templates which implement + a network service. Service exists to provide a + singular abstraction which can be access controlled, + reasoned about, and which encapsulates software + lifecycle decisions such as rollout policy and team + resource ownership. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 = gcr_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=15.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcr_service.Service, + metadata_type=gcr_service.Service, + ) + + # Done; return the response. + return response + + async def get_service(self, + request: Union[service.GetServiceRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets information about a Service. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_get_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.GetServiceRequest, dict]): + The request object. Request message for obtaining a + Service by its full name. + name (:class:`str`): + Required. The full name of the + Service. Format: + projects/{projectnumber}/locations/{location}/services/{service} + + 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.run_v2.types.Service: + Service acts as a top-level container + that manages a set of configurations and + revision templates which implement a + network service. Service exists to + provide a singular abstraction which can + be access controlled, reasoned about, + and which encapsulates software + lifecycle decisions such as rollout + policy and team resource ownership. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.GoogleAPICallError, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_services(self, + request: Union[service.ListServicesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesAsyncPager: + r"""List Services. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_list_services(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.run_v2.types.ListServicesRequest, dict]): + The request object. Request message for retrieving a + list of Services. + parent (:class:`str`): + Required. The location and project to + list resources on. Location must be a + valid GCP region, and may not be the "-" + wildcard. Format: + projects/{projectnumber}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.run_v2.services.services.pagers.ListServicesAsyncPager: + Response message containing a list of + Services. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.GoogleAPICallError, + ), + deadline=10.0, + ), + default_timeout=10.0, + 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 update_service(self, + request: Union[gcr_service.UpdateServiceRequest, dict] = None, + *, + service: gcr_service.Service = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a Service. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_update_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.UpdateServiceRequest, dict]): + The request object. Request message for updating a + service. + service (:class:`google.cloud.run_v2.types.Service`): + Required. The Service to be updated. + 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`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of + configurations and revision templates which implement + a network service. Service exists to provide a + singular abstraction which can be access controlled, + reasoned about, and which encapsulates software + lifecycle decisions such as rollout policy and team + resource ownership. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, 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 = gcr_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=15.0, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcr_service.Service, + metadata_type=gcr_service.Service, + ) + + # Done; return the response. + return response + + async def delete_service(self, + request: Union[service.DeleteServiceRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a Service. + This will cause the Service to stop serving traffic and + will delete all revisions. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_delete_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.DeleteServiceRequest, dict]): + The request object. Request message to delete a Service + by its full name. + name (:class:`str`): + Required. The full name of the + Service. Format: + projects/{projectnumber}/locations/{location}/services/{service} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of + configurations and revision templates which implement + a network service. Service exists to provide a + singular abstraction which can be access controlled, + reasoned about, and which encapsulates software + lifecycle decisions such as rollout policy and team + resource ownership. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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=10.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + service.Service, + metadata_type=service.Service, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Get the IAM Access Control policy currently in effect + for the given Cloud Run Service. This result does not + include any inherited policies. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_get_iam_policy(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + 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: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ 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: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM Access control policy for the specified + Service. Overwrites any existing policy. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_set_iam_policy(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + 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: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ 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: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns permissions that a caller has on the + specified Project. + There are no permissions required for making this API + call. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_test_iam_permissions(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value_1', 'permissions_value_2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + 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. + # 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-run", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServicesAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/client.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/client.py new file mode 100644 index 0000000..9caff13 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/services/client.py @@ -0,0 +1,1405 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.run_v2.services.services import pagers +from google.cloud.run_v2.types import condition +from google.cloud.run_v2.types import revision_template +from google.cloud.run_v2.types import service +from google.cloud.run_v2.types import service as gcr_service +from google.cloud.run_v2.types import traffic_target +from google.cloud.run_v2.types import vendor_settings +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 ServicesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ServicesGrpcTransport +from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport + + +class ServicesClientMeta(type): + """Metaclass for the Services 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[ServicesTransport]] + _transport_registry["grpc"] = ServicesGrpcTransport + _transport_registry["grpc_asyncio"] = ServicesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ServicesTransport]: + """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 ServicesClient(metaclass=ServicesClientMeta): + """Cloud Run Service Control Plane API""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "run.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: + ServicesClient: 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: + ServicesClient: 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) -> ServicesTransport: + """Returns the transport used by the client instance. + + Returns: + ServicesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def connector_path(project: str,location: str,connector: str,) -> str: + """Returns a fully-qualified connector string.""" + return "projects/{project}/locations/{location}/connectors/{connector}".format(project=project, location=location, connector=connector, ) + + @staticmethod + def parse_connector_path(path: str) -> Dict[str,str]: + """Parses a connector path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/connectors/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str,str]: + """Parses a crypto_key path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def revision_path(project: str,location: str,service: str,revision: str,) -> str: + """Returns a fully-qualified revision string.""" + return "projects/{project}/locations/{location}/services/{service}/revisions/{revision}".format(project=project, location=location, service=service, revision=revision, ) + + @staticmethod + def parse_revision_path(path: str) -> Dict[str,str]: + """Parses a revision path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)/revisions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def secret_path(project: str,secret: str,) -> str: + """Returns a fully-qualified secret string.""" + return "projects/{project}/secrets/{secret}".format(project=project, secret=secret, ) + + @staticmethod + def parse_secret_path(path: str) -> Dict[str,str]: + """Parses a secret path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def secret_version_path(project: str,secret: str,version: str,) -> str: + """Returns a fully-qualified secret_version string.""" + return "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) + + @staticmethod + def parse_secret_version_path(path: str) -> Dict[str,str]: + """Parses a secret_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, 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.+?)/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 {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ServicesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the services 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, ServicesTransport]): 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() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ServicesTransport): + # transport is a ServicesTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_service(self, + request: Union[gcr_service.CreateServiceRequest, dict] = None, + *, + parent: str = None, + service: gcr_service.Service = None, + service_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Service in a given project and + location. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_create_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.CreateServiceRequest, dict]): + The request object. Request message for creating a + Service. + parent (str): + Required. The location and project in + which this service should be created. + Format: + projects/{projectnumber}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (google.cloud.run_v2.types.Service): + Required. The Service instance to + create. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (str): + Required. The unique identifier for the Service. The + name of the service becomes + {parent}/services/{service_id}. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of + configurations and revision templates which implement + a network service. Service exists to provide a + singular abstraction which can be access controlled, + reasoned about, and which encapsulates software + lifecycle decisions such as rollout policy and team + resource ownership. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 gcr_service.CreateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcr_service.CreateServiceRequest): + request = gcr_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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcr_service.Service, + metadata_type=gcr_service.Service, + ) + + # Done; return the response. + return response + + def get_service(self, + request: Union[service.GetServiceRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets information about a Service. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_get_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.GetServiceRequest, dict]): + The request object. Request message for obtaining a + Service by its full name. + name (str): + Required. The full name of the + Service. Format: + projects/{projectnumber}/locations/{location}/services/{service} + + 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.run_v2.types.Service: + Service acts as a top-level container + that manages a set of configurations and + revision templates which implement a + network service. Service exists to + provide a singular abstraction which can + be access controlled, reasoned about, + and which encapsulates software + lifecycle decisions such as rollout + policy and team resource ownership. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetServiceRequest): + request = 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 list_services(self, + request: Union[service.ListServicesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesPager: + r"""List Services. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_list_services(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.run_v2.types.ListServicesRequest, dict]): + The request object. Request message for retrieving a + list of Services. + parent (str): + Required. The location and project to + list resources on. Location must be a + valid GCP region, and may not be the "-" + wildcard. Format: + projects/{projectnumber}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.run_v2.services.services.pagers.ListServicesPager: + Response message containing a list of + Services. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListServicesRequest): + request = 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 update_service(self, + request: Union[gcr_service.UpdateServiceRequest, dict] = None, + *, + service: gcr_service.Service = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates a Service. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_update_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.UpdateServiceRequest, dict]): + The request object. Request message for updating a + service. + service (google.cloud.run_v2.types.Service): + Required. The Service to be updated. + 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): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of + configurations and revision templates which implement + a network service. Service exists to provide a + singular abstraction which can be access controlled, + reasoned about, and which encapsulates software + lifecycle decisions such as rollout policy and team + resource ownership. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, 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 gcr_service.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcr_service.UpdateServiceRequest): + request = gcr_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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcr_service.Service, + metadata_type=gcr_service.Service, + ) + + # Done; return the response. + return response + + def delete_service(self, + request: Union[service.DeleteServiceRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a Service. + This will cause the Service to stop serving traffic and + will delete all revisions. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_delete_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.DeleteServiceRequest, dict]): + The request object. Request message to delete a Service + by its full name. + name (str): + Required. The full name of the + Service. Format: + projects/{projectnumber}/locations/{location}/services/{service} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of + configurations and revision templates which implement + a network service. Service exists to provide a + singular abstraction which can be access controlled, + reasoned about, and which encapsulates software + lifecycle decisions such as rollout policy and team + resource ownership. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.DeleteServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteServiceRequest): + request = 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + service.Service, + metadata_type=service.Service, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Get the IAM Access Control policy currently in effect + for the given Cloud Run Service. This result does not + include any inherited policies. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_get_iam_policy(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + 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: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ 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: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM Access control policy for the specified + Service. Overwrites any existing policy. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_set_iam_policy(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + 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: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ 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: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns permissions that a caller has on the + specified Project. + There are no permissions required for making this API + call. + + .. code-block:: python + + from google.cloud import run_v2 + + def sample_test_iam_permissions(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value_1', 'permissions_value_2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + 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-run", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServicesClient", +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/pagers.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/pagers.py new file mode 100644 index 0000000..b411cdd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/services/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.run_v2.types import service + + +class ListServicesPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.run_v2.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.run_v2.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[..., service.ListServicesResponse], + request: service.ListServicesRequest, + response: 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.run_v2.types.ListServicesRequest): + The initial request object. + response (google.cloud.run_v2.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 = 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[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.run_v2.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.run_v2.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[service.ListServicesResponse]], + request: service.ListServicesRequest, + response: 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.run_v2.types.ListServicesRequest): + The initial request object. + response (google.cloud.run_v2.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 = 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[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) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/__init__.py new file mode 100644 index 0000000..f5bea72 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ServicesTransport +from .grpc import ServicesGrpcTransport +from .grpc_asyncio import ServicesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ServicesTransport]] +_transport_registry['grpc'] = ServicesGrpcTransport +_transport_registry['grpc_asyncio'] = ServicesGrpcAsyncIOTransport + +__all__ = ( + 'ServicesTransport', + 'ServicesGrpcTransport', + 'ServicesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/base.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/base.py new file mode 100644 index 0000000..f0ebc1b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/base.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.run_v2.types import service +from google.cloud.run_v2.types import service as gcr_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-run', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ServicesTransport(abc.ABC): + """Abstract transport class for Services.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'run.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_service: gapic_v1.method.wrap_method( + self.create_service, + default_timeout=15.0, + client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.GoogleAPICallError, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.list_services: gapic_v1.method.wrap_method( + self.list_services, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.GoogleAPICallError, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, + default_timeout=15.0, + client_info=client_info, + ), + self.delete_service: gapic_v1.method.wrap_method( + self.delete_service, + default_timeout=10.0, + 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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_service(self) -> Callable[ + [gcr_service.CreateServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_service(self) -> Callable[ + [service.GetServiceRequest], + Union[ + service.Service, + Awaitable[service.Service] + ]]: + raise NotImplementedError() + + @property + def list_services(self) -> Callable[ + [service.ListServicesRequest], + Union[ + service.ListServicesResponse, + Awaitable[service.ListServicesResponse] + ]]: + raise NotImplementedError() + + @property + def update_service(self) -> Callable[ + [gcr_service.UpdateServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_service(self) -> Callable[ + [service.DeleteServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ServicesTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc.py new file mode 100644 index 0000000..e0ec942 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc.py @@ -0,0 +1,475 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.run_v2.types import service +from google.cloud.run_v2.types import service as gcr_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import ServicesTransport, DEFAULT_CLIENT_INFO + + +class ServicesGrpcTransport(ServicesTransport): + """gRPC backend transport for Services. + + Cloud Run Service Control Plane API + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'run.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'run.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_service(self) -> Callable[ + [gcr_service.CreateServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create service method over gRPC. + + Creates a new Service in a given project and + location. + + Returns: + Callable[[~.CreateServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Services/CreateService', + request_serializer=gcr_service.CreateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_service'] + + @property + def get_service(self) -> Callable[ + [service.GetServiceRequest], + service.Service]: + r"""Return a callable for the get service method over gRPC. + + Gets information about 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.run.v2.Services/GetService', + request_serializer=service.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def list_services(self) -> Callable[ + [service.ListServicesRequest], + service.ListServicesResponse]: + r"""Return a callable for the list services method over gRPC. + + List Services. + + 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.run.v2.Services/ListServices', + request_serializer=service.ListServicesRequest.serialize, + response_deserializer=service.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def update_service(self) -> Callable[ + [gcr_service.UpdateServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the update service method over gRPC. + + Updates a Service. + + Returns: + Callable[[~.UpdateServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Services/UpdateService', + request_serializer=gcr_service.UpdateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [service.DeleteServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a Service. + This will cause the Service to stop serving traffic and + will delete all revisions. + + Returns: + Callable[[~.DeleteServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Services/DeleteService', + request_serializer=service.DeleteServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service'] + + @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. + + Get the IAM Access Control policy currently in effect + for the given Cloud Run Service. This result does not + include any inherited policies. + + 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.run.v2.Services/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 Access control policy for the specified + Service. Overwrites any existing policy. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Services/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. + + Returns permissions that a caller has on the + specified Project. + There are no permissions required for making this API + call. + + 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.run.v2.Services/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() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ServicesGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc_asyncio.py new file mode 100644 index 0000000..86b95d0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc_asyncio.py @@ -0,0 +1,474 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.run_v2.types import service +from google.cloud.run_v2.types import service as gcr_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import ServicesTransport, DEFAULT_CLIENT_INFO +from .grpc import ServicesGrpcTransport + + +class ServicesGrpcAsyncIOTransport(ServicesTransport): + """gRPC AsyncIO backend transport for Services. + + Cloud Run Service Control Plane API + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'run.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 = 'run.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_service(self) -> Callable[ + [gcr_service.CreateServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create service method over gRPC. + + Creates a new Service in a given project and + location. + + Returns: + Callable[[~.CreateServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Services/CreateService', + request_serializer=gcr_service.CreateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_service'] + + @property + def get_service(self) -> Callable[ + [service.GetServiceRequest], + Awaitable[service.Service]]: + r"""Return a callable for the get service method over gRPC. + + Gets information about 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.run.v2.Services/GetService', + request_serializer=service.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def list_services(self) -> Callable[ + [service.ListServicesRequest], + Awaitable[service.ListServicesResponse]]: + r"""Return a callable for the list services method over gRPC. + + List Services. + + 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.run.v2.Services/ListServices', + request_serializer=service.ListServicesRequest.serialize, + response_deserializer=service.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def update_service(self) -> Callable[ + [gcr_service.UpdateServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update service method over gRPC. + + Updates a Service. + + Returns: + Callable[[~.UpdateServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Services/UpdateService', + request_serializer=gcr_service.UpdateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [service.DeleteServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a Service. + This will cause the Service to stop serving traffic and + will delete all revisions. + + Returns: + Callable[[~.DeleteServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.run.v2.Services/DeleteService', + request_serializer=service.DeleteServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service'] + + @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. + + Get the IAM Access Control policy currently in effect + for the given Cloud Run Service. This result does not + include any inherited policies. + + 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.run.v2.Services/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 Access control policy for the specified + Service. Overwrites any existing policy. + + 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.run.v2.Services/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. + + Returns permissions that a caller has on the + specified Project. + There are no permissions required for making this API + call. + + 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.run.v2.Services/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__ = ( + 'ServicesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/types/__init__.py new file mode 100644 index 0000000..e6ddcc2 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/types/__init__.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .condition import ( + Condition, +) +from .k8s_min import ( + CloudSqlInstance, + Container, + ContainerPort, + EnvVar, + EnvVarSource, + ResourceRequirements, + SecretKeySelector, + SecretVolumeSource, + VersionToPath, + Volume, + VolumeMount, +) +from .revision import ( + DeleteRevisionRequest, + GetRevisionRequest, + ListRevisionsRequest, + ListRevisionsResponse, + Revision, +) +from .revision_template import ( + RevisionTemplate, +) +from .service import ( + CreateServiceRequest, + DeleteServiceRequest, + GetServiceRequest, + ListServicesRequest, + ListServicesResponse, + Service, + UpdateServiceRequest, +) +from .traffic_target import ( + TrafficTarget, + TrafficTargetStatus, + TrafficTargetAllocationType, +) +from .vendor_settings import ( + BinaryAuthorization, + RevisionScaling, + VpcAccess, + ExecutionEnvironment, + IngressTraffic, +) + +__all__ = ( + 'Condition', + 'CloudSqlInstance', + 'Container', + 'ContainerPort', + 'EnvVar', + 'EnvVarSource', + 'ResourceRequirements', + 'SecretKeySelector', + 'SecretVolumeSource', + 'VersionToPath', + 'Volume', + 'VolumeMount', + 'DeleteRevisionRequest', + 'GetRevisionRequest', + 'ListRevisionsRequest', + 'ListRevisionsResponse', + 'Revision', + 'RevisionTemplate', + 'CreateServiceRequest', + 'DeleteServiceRequest', + 'GetServiceRequest', + 'ListServicesRequest', + 'ListServicesResponse', + 'Service', + 'UpdateServiceRequest', + 'TrafficTarget', + 'TrafficTargetStatus', + 'TrafficTargetAllocationType', + 'BinaryAuthorization', + 'RevisionScaling', + 'VpcAccess', + 'ExecutionEnvironment', + 'IngressTraffic', +) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/condition.py b/owl-bot-staging/v2/google/cloud/run_v2/types/condition.py new file mode 100644 index 0000000..15c76f0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/types/condition.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.run.v2', + manifest={ + 'Condition', + }, +) + + +class Condition(proto.Message): + r"""Defines a status condition for a resource. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (str): + type is used to communicate the status of the reconciliation + process. See also: + https://github.com/knative/serving/blob/main/docs/spec/errors.md#error-conditions-and-reporting + Types common to all resources include: + + - "Ready": True when the Resource is ready. + state (google.cloud.run_v2.types.Condition.State): + State of the condition. + message (str): + Human readable message indicating details + about the current status. + last_transition_time (google.protobuf.timestamp_pb2.Timestamp): + Last time the condition transitioned from one + status to another. + severity (google.cloud.run_v2.types.Condition.Severity): + How to interpret failures of this condition, + one of Error, Warning, Info + reason (google.cloud.run_v2.types.Condition.CommonReason): + A common (service-level) reason for this + condition. + + This field is a member of `oneof`_ ``reasons``. + internal_reason (google.cloud.run_v2.types.Condition.InternalReason): + A reason for the internal condition. + + This field is a member of `oneof`_ ``reasons``. + domain_mapping_reason (google.cloud.run_v2.types.Condition.DomainMappingReason): + A reason for the domain mapping condition. + + This field is a member of `oneof`_ ``reasons``. + revision_reason (google.cloud.run_v2.types.Condition.RevisionReason): + A reason for the revision condition. + + This field is a member of `oneof`_ ``reasons``. + execution_reason (google.cloud.run_v2.types.Condition.ExecutionReason): + A reason for the execution condition. + + This field is a member of `oneof`_ ``reasons``. + """ + class State(proto.Enum): + r"""Represents the possible Condition states.""" + STATE_UNSPECIFIED = 0 + CONDITION_PENDING = 1 + CONDITION_RECONCILING = 2 + CONDITION_FAILED = 3 + CONDITION_SUCCEEDED = 4 + + class Severity(proto.Enum): + r"""Represents the severity of the condition failures.""" + SEVERITY_UNSPECIFIED = 0 + ERROR = 1 + WARNING = 2 + INFO = 3 + + class CommonReason(proto.Enum): + r"""Reasons common to all types of conditions.""" + COMMON_REASON_UNDEFINED = 0 + UNKNOWN = 1 + ROUTE_MISSING = 2 + REVISION_FAILED = 3 + PROGRESS_DEADLINE_EXCEEDED = 4 + BUILD_STEP_FAILED = 5 + CONTAINER_MISSING = 6 + CONTAINER_PERMISSION_DENIED = 7 + CONTAINER_IMAGE_UNAUTHORIZED = 8 + CONTAINER_IMAGE_AUTHORIZATION_CHECK_FAILED = 9 + ENCRYPTION_KEY_PERMISSION_DENIED = 10 + ENCRYPTION_KEY_CHECK_FAILED = 11 + SECRETS_ACCESS_CHECK_FAILED = 12 + WAITING_FOR_OPERATION = 13 + IMMEDIATE_RETRY = 14 + POSTPONED_RETRY = 15 + + class InternalReason(proto.Enum): + r"""Reasons applicable to internal resources not exposed to + users. These will surface in Service.conditions, and could be + useful for further diagnosis. + """ + INTERNAL_REASON_UNDEFINED = 0 + CONFLICTING_REVISION_NAME = 1 + REVISION_MISSING = 2 + CONFIGURATION_MISSING = 3 + ASSIGNING_TRAFFIC = 4 + UPDATING_INGRESS_TRAFFIC_ALLOWED = 5 + REVISION_ORG_POLICY_VIOLATION = 6 + ENABLING_GCFV2_URI_SUPPORT = 7 + + class DomainMappingReason(proto.Enum): + r"""Reasons specific to DomainMapping resource.""" + DOMAIN_MAPPING_REASON_UNDEFINED = 0 + ROUTE_NOT_READY = 1 + PERMISSION_DENIED = 2 + CERTIFICATE_ALREADY_EXISTS = 3 + MAPPING_ALREADY_EXISTS = 4 + CERTIFICATE_PENDING = 5 + CERTIFICATE_FAILED = 6 + + class RevisionReason(proto.Enum): + r"""Reasons specific to Revision resource.""" + REVISION_REASON_UNDEFINED = 0 + PENDING = 1 + RESERVE = 2 + RETIRED = 3 + RETIRING = 4 + RECREATING = 5 + HEALTH_CHECK_CONTAINER_ERROR = 6 + CUSTOMIZED_PATH_RESPONSE_PENDING = 7 + MIN_INSTANCES_NOT_PROVISIONED = 8 + ACTIVE_REVISION_LIMIT_REACHED = 9 + NO_DEPLOYMENT = 10 + HEALTH_CHECK_SKIPPED = 11 + + class ExecutionReason(proto.Enum): + r"""Reasons specific to Execution resource.""" + EXECUTION_REASON_UNDEFINED = 0 + JOB_STATUS_SERVICE_POLLING_ERROR = 1 + NON_ZERO_EXIT_CODE = 2 + + type_ = proto.Field( + proto.STRING, + number=1, + ) + state = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + message = proto.Field( + proto.STRING, + number=3, + ) + last_transition_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + severity = proto.Field( + proto.ENUM, + number=5, + enum=Severity, + ) + reason = proto.Field( + proto.ENUM, + number=6, + oneof='reasons', + enum=CommonReason, + ) + internal_reason = proto.Field( + proto.ENUM, + number=7, + oneof='reasons', + enum=InternalReason, + ) + domain_mapping_reason = proto.Field( + proto.ENUM, + number=8, + oneof='reasons', + enum=DomainMappingReason, + ) + revision_reason = proto.Field( + proto.ENUM, + number=9, + oneof='reasons', + enum=RevisionReason, + ) + execution_reason = proto.Field( + proto.ENUM, + number=11, + oneof='reasons', + enum=ExecutionReason, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/k8s_min.py b/owl-bot-staging/v2/google/cloud/run_v2/types/k8s_min.py new file mode 100644 index 0000000..fab6a76 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/types/k8s_min.py @@ -0,0 +1,477 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.run.v2', + manifest={ + 'Container', + 'ResourceRequirements', + 'EnvVar', + 'EnvVarSource', + 'SecretKeySelector', + 'ContainerPort', + 'VolumeMount', + 'Volume', + 'SecretVolumeSource', + 'VersionToPath', + 'CloudSqlInstance', + }, +) + + +class Container(proto.Message): + r"""A single application container. + This specifies both the container to run, the command to run in + the container and the arguments to supply to it. + Note that additional arguments may be supplied by the system to + the container at runtime. + + Attributes: + name (str): + Name of the container specified as a DNS_LABEL. + image (str): + Required. URL of the Container image in + Google Container Registry or Docker More info: + https://kubernetes.io/docs/concepts/containers/images + command (Sequence[str]): + Entrypoint array. Not executed within a shell. The docker + image's ENTRYPOINT is used if this is not provided. Variable + references $(VAR_NAME) are expanded using the container's + environment. If a variable cannot be resolved, the reference + in the input string will be unchanged. The $(VAR_NAME) + syntax can be escaped with a double $$, ie: $$(VAR_NAME). + Escaped references will never be expanded, regardless of + whether the variable exists or not. More info: + https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell + args (Sequence[str]): + Arguments to the entrypoint. The docker image's CMD is used + if this is not provided. Variable references $(VAR_NAME) are + expanded using the container's environment. If a variable + cannot be resolved, the reference in the input string will + be unchanged. The $(VAR_NAME) syntax can be escaped with a + double $$, ie: $$(VAR_NAME). Escaped references will never + be expanded, regardless of whether the variable exists or + not. More info: + https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell + env (Sequence[google.cloud.run_v2.types.EnvVar]): + List of environment variables to set in the + container. + resources (google.cloud.run_v2.types.ResourceRequirements): + Compute Resource requirements by this + container. More info: + https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources + ports (Sequence[google.cloud.run_v2.types.ContainerPort]): + List of ports to expose from the container. + Only a single port can be specified. The + specified ports must be listening on all + interfaces (0.0.0.0) within the container to be + accessible. + If omitted, a port number will be chosen and + passed to the container through the PORT + environment variable for the container to listen + on. + volume_mounts (Sequence[google.cloud.run_v2.types.VolumeMount]): + Volume to mount into the container's + filesystem. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + image = proto.Field( + proto.STRING, + number=2, + ) + command = proto.RepeatedField( + proto.STRING, + number=3, + ) + args = proto.RepeatedField( + proto.STRING, + number=4, + ) + env = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='EnvVar', + ) + resources = proto.Field( + proto.MESSAGE, + number=6, + message='ResourceRequirements', + ) + ports = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ContainerPort', + ) + volume_mounts = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='VolumeMount', + ) + + +class ResourceRequirements(proto.Message): + r"""ResourceRequirements describes the compute resource + requirements. + + Attributes: + limits (Mapping[str, str]): + Only memory and CPU are supported. Note: The + only supported values for CPU are '1', '2', and + '4'. Setting 4 CPU requires at least 2Gi of + memory. + The values of the map is string form of the + 'quantity' k8s type: + https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go + cpu_idle (bool): + Determines whether CPU should be throttled or + not outside of requests. + """ + + limits = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + cpu_idle = proto.Field( + proto.BOOL, + number=2, + ) + + +class EnvVar(proto.Message): + r"""EnvVar represents an environment variable present in a + Container. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of the environment variable. Must be a + C_IDENTIFIER, and mnay not exceed 32768 characters. + value (str): + Variable references $(VAR_NAME) are expanded using the + previous defined environment variables in the container and + any route environment variables. If a variable cannot be + resolved, the reference in the input string will be + unchanged. The $(VAR_NAME) syntax can be escaped with a + double $$, ie: $$(VAR_NAME). Escaped references will never + be expanded, regardless of whether the variable exists or + not. Defaults to "", and the maximum length is 32768 bytes. + + This field is a member of `oneof`_ ``values``. + value_source (google.cloud.run_v2.types.EnvVarSource): + Source for the environment variable's value. + + This field is a member of `oneof`_ ``values``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.STRING, + number=2, + oneof='values', + ) + value_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='values', + message='EnvVarSource', + ) + + +class EnvVarSource(proto.Message): + r"""EnvVarSource represents a source for the value of an EnvVar. + + Attributes: + secret_key_ref (google.cloud.run_v2.types.SecretKeySelector): + Selects a secret and a specific version from + Cloud Secret Manager. + """ + + secret_key_ref = proto.Field( + proto.MESSAGE, + number=1, + message='SecretKeySelector', + ) + + +class SecretKeySelector(proto.Message): + r"""SecretEnvVarSource represents a source for the value of an + EnvVar. + + Attributes: + secret (str): + Required. The name of the secret in Cloud Secret Manager. + Format: {secret_name} if the secret is in the same project. + projects/{project}/secrets/{secret_name} if the secret is in + a different project. + version (str): + The Cloud Secret Manager secret version. + Can be 'latest' for the latest value or an + integer for a specific version. + """ + + secret = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.STRING, + number=2, + ) + + +class ContainerPort(proto.Message): + r"""ContainerPort represents a network port in a single + container. + + Attributes: + name (str): + If specified, used to specify which protocol + to use. Allowed values are "http1" and "h2c". + container_port (int): + Port number the container listens on. This must be a valid + TCP port number, 0 < container_port < 65536. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + container_port = proto.Field( + proto.INT32, + number=3, + ) + + +class VolumeMount(proto.Message): + r"""VolumeMount describes a mounting of a Volume within a + container. + + Attributes: + name (str): + Required. This must match the Name of a + Volume. + mount_path (str): + Required. Path within the container at which the volume + should be mounted. Must not contain ':'. For Cloud SQL + volumes, it can be left empty, or must otherwise be + ``/cloudsql``. All instances defined in the Volume will be + available as ``/cloudsql/[instance]``. For more information + on Cloud SQL volumes, visit + https://cloud.google.com/sql/docs/mysql/connect-run + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + mount_path = proto.Field( + proto.STRING, + number=3, + ) + + +class Volume(proto.Message): + r"""Volume represents a named volume in a container. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Volume's name. + secret (google.cloud.run_v2.types.SecretVolumeSource): + Secret represents a secret that should + populate this volume. More info: + https://kubernetes.io/docs/concepts/storage/volumes#secret + + This field is a member of `oneof`_ ``volume_type``. + cloud_sql_instance (google.cloud.run_v2.types.CloudSqlInstance): + For Cloud SQL volumes, contains the specific + instances that should be mounted. Visit + https://cloud.google.com/sql/docs/mysql/connect-run + for more information on how to connect Cloud SQL + and Cloud Run. + + This field is a member of `oneof`_ ``volume_type``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + secret = proto.Field( + proto.MESSAGE, + number=2, + oneof='volume_type', + message='SecretVolumeSource', + ) + cloud_sql_instance = proto.Field( + proto.MESSAGE, + number=3, + oneof='volume_type', + message='CloudSqlInstance', + ) + + +class SecretVolumeSource(proto.Message): + r"""The secret's value will be presented as the content of a file + whose name is defined in the item path. If no items are defined, + the name of the file is the secret. + + Attributes: + secret (str): + Required. The name of the secret in Cloud + Secret Manager. Format: {secret} if the secret + is in the same project. + projects/{project}/secrets/{secret} if the + secret is in a different project. + items (Sequence[google.cloud.run_v2.types.VersionToPath]): + If unspecified, the volume will expose a file whose name is + the secret, relative to VolumeMount.mount_path. If + specified, the key will be used as the version to fetch from + Cloud Secret Manager and the path will be the name of the + file exposed in the volume. When items are defined, they + must specify a path and a version. + default_mode (int): + Integer representation of mode bits to use on created files + by default. Must be a value between 0000 and 0777 (octal), + defaulting to 0644. Directories within the path are not + affected by this setting. + + Notes + + - Internally, a umask of 0222 will be applied to any + non-zero value. + - This is an integer representation of the mode bits. So, + the octal integer value should look exactly as the chmod + numeric notation with a leading zero. Some examples: for + chmod 777 (a=rwx), set to 0777 (octal) or 511 (base-10). + For chmod 640 (u=rw,g=r), set to 0640 (octal) or 416 + (base-10). For chmod 755 (u=rwx,g=rx,o=rx), set to 0755 + (octal) or 493 (base-10). + - This might be in conflict with other options that affect + the file mode, like fsGroup, and the result can be other + mode bits set. + + This might be in conflict with other options that affect the + file mode, like fsGroup, and as a result, other mode bits + could be set. + """ + + secret = proto.Field( + proto.STRING, + number=1, + ) + items = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='VersionToPath', + ) + default_mode = proto.Field( + proto.INT32, + number=3, + ) + + +class VersionToPath(proto.Message): + r"""VersionToPath maps a specific version of a secret to a relative file + to mount to, relative to VolumeMount's mount_path. + + Attributes: + path (str): + Required. The relative path of the secret in + the container. + version (str): + The Cloud Secret Manager secret version. + Can be 'latest' for the latest value or an + integer for a specific version. + mode (int): + Integer octal mode bits to use on this file, must be a value + between 01 and 0777 (octal). If 0 or not set, the Volume's + default mode will be used. + + Notes + + - Internally, a umask of 0222 will be applied to any + non-zero value. + - This is an integer representation of the mode bits. So, + the octal integer value should look exactly as the chmod + numeric notation with a leading zero. Some examples: for + chmod 777 (a=rwx), set to 0777 (octal) or 511 (base-10). + For chmod 640 (u=rw,g=r), set to 0640 (octal) or 416 + (base-10). For chmod 755 (u=rwx,g=rx,o=rx), set to 0755 + (octal) or 493 (base-10). + - This might be in conflict with other options that affect + the file mode, like fsGroup, and the result can be other + mode bits set. + """ + + path = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.STRING, + number=2, + ) + mode = proto.Field( + proto.INT32, + number=3, + ) + + +class CloudSqlInstance(proto.Message): + r"""Represents a specific Cloud SQL instance. + + Attributes: + connections (Sequence[str]): + The Cloud SQL instance connection names, as + can be found in + https://console.cloud.google.com/sql/instances. + Visit + https://cloud.google.com/sql/docs/mysql/connect-run + for more information on how to connect Cloud SQL + and Cloud Run. Format: + {project}:{location}:{instance} + """ + + connections = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/revision.py b/owl-bot-staging/v2/google/cloud/run_v2/types/revision.py new file mode 100644 index 0000000..1fc0fee --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/types/revision.py @@ -0,0 +1,388 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.api import launch_stage_pb2 # type: ignore +from google.cloud.run_v2.types import condition +from google.cloud.run_v2.types import k8s_min +from google.cloud.run_v2.types import vendor_settings +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.run.v2', + manifest={ + 'GetRevisionRequest', + 'ListRevisionsRequest', + 'ListRevisionsResponse', + 'DeleteRevisionRequest', + 'Revision', + }, +) + + +class GetRevisionRequest(proto.Message): + r"""Request message for obtaining a Revision by its full name. + + Attributes: + name (str): + Required. The full name of the Revision. + Format: + projects/{project}/locations/{location}/services/{service}/revisions/{revision} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRevisionsRequest(proto.Message): + r"""Request message for retrieving a list of Revisions. + + Attributes: + parent (str): + Required. The Service from which the + Revisions should be listed. To list all + Revisions across Services, use "-" instead of + Service name. Format: + projects/{project}/locations/{location}/services/{service} + page_size (int): + Maximum number of revisions to return in this + call. + page_token (str): + A page token received from a previous call to + ListRevisions. All other parameters must match. + show_deleted (bool): + If true, returns deleted (but unexpired) + resources along with active ones. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + show_deleted = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListRevisionsResponse(proto.Message): + r"""Response message containing a list of Revisions. + + Attributes: + revisions (Sequence[google.cloud.run_v2.types.Revision]): + The resulting list of Revisions. + next_page_token (str): + A token indicating there are more items than page_size. Use + it in the next ListRevisions request to continue. + """ + + @property + def raw_page(self): + return self + + revisions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Revision', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteRevisionRequest(proto.Message): + r"""Request message for deleting a retired Revision. + Revision lifecycle is usually managed by making changes to the + parent Service. Only retired revisions can be deleted with this + API. + + Attributes: + name (str): + Required. The name of the Revision to delete. + Format: + projects/{project}/locations/{location}/services/{service}/revisions/{revision} + validate_only (bool): + Indicates that the request should be + validated without actually deleting any + resources. + etag (str): + A system-generated fingerprint for this + version of the resource. This may be used to + detect modification conflict during updates. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + validate_only = proto.Field( + proto.BOOL, + number=2, + ) + etag = proto.Field( + proto.STRING, + number=3, + ) + + +class Revision(proto.Message): + r"""A Revision is an immutable snapshot of code and + configuration. A Revision references a container image. + Revisions are only created by updates to its parent Service. + + Attributes: + name (str): + Output only. The unique name of this + Revision. + uid (str): + Output only. Server assigned unique + identifier for the Revision. The value is a + UUID4 string and guaranteed to remain unchanged + until the resource is deleted. + generation (int): + Output only. A number that monotonically + increases every time the user modifies the + desired state. + labels (Mapping[str, str]): + KRM-style labels for the resource. + User-provided labels are shared with Google's + billing system, so they can be used to filter, + or break down billing charges by team, + component, environment, state, etc. For more + information, visit + https://cloud.google.com/resource-manager/docs/creating-managing-labels + or + https://cloud.google.com/run/docs/configuring/labels + Cloud Run will populate some labels with + 'run.googleapis.com' or 'serving.knative.dev' + namespaces. Those labels are read-only, and user + changes will not be preserved. + annotations (Mapping[str, str]): + KRM-style annotations for the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last-modified time. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. For a deleted resource, the + deletion time. It is only populated as a + response to a Delete request. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. For a deleted resource, the time + after which it will be permamently deleted. It + is only populated as a response to a Delete + request. + launch_stage (google.api.launch_stage_pb2.LaunchStage): + Set the launch stage to a preview stage on write to allow + use of preview features in that stage. On read, describes + whether the resource uses preview features. Launch Stages + are defined at `Google Cloud Platform Launch + Stages `__. + service (str): + Output only. The name of the parent service. + scaling (google.cloud.run_v2.types.RevisionScaling): + Scaling settings for this revision. + vpc_access (google.cloud.run_v2.types.VpcAccess): + VPC Access configuration for this Revision. + For more information, visit + https://cloud.google.com/run/docs/configuring/connecting-vpc. + container_concurrency (int): + Sets the maximum number of requests that each + serving instance can receive. + timeout (google.protobuf.duration_pb2.Duration): + Max allowed time for an instance to respond + to a request. + service_account (str): + Email address of the IAM service account + associated with the revision of the service. The + service account represents the identity of the + running revision, and determines what + permissions the revision has. + containers (Sequence[google.cloud.run_v2.types.Container]): + Holds the single container that defines the + unit of execution for this Revision. + volumes (Sequence[google.cloud.run_v2.types.Volume]): + A list of Volumes to make available to + containers. + confidential (bool): + Indicates whether Confidential Cloud Run is + enabled in this Revision. + execution_environment (google.cloud.run_v2.types.ExecutionEnvironment): + The execution environment being used to host + this Revision. + encryption_key (str): + A reference to a customer managed encryption + key (CMEK) to use to encrypt this container + image. For more information, go to + https://cloud.google.com/run/docs/securing/using-cmek + reconciling (bool): + Output only. Indicates whether the resource's reconciliation + is still in progress. See comments in + ``Service.reconciling`` for additional information on + reconciliation process in Cloud Run. + conditions (Sequence[google.cloud.run_v2.types.Condition]): + Output only. The Condition of this Revision, + containing its readiness status, and detailed + error information in case it did not reach a + serving state. + observed_generation (int): + Output only. The generation of this Revision currently + serving traffic. See comments in ``reconciling`` for + additional information on reconciliation process in Cloud + Run. + log_uri (str): + Output only. The Google Console URI to obtain + logs for the Revision. + etag (str): + Output only. A system-generated fingerprint + for this version of the resource. May be used to + detect modification conflict during updates. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + uid = proto.Field( + proto.STRING, + number=2, + ) + generation = proto.Field( + proto.INT64, + number=3, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations = proto.MapField( + proto.STRING, + 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, + ) + delete_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + expire_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + launch_stage = proto.Field( + proto.ENUM, + number=10, + enum=launch_stage_pb2.LaunchStage, + ) + service = proto.Field( + proto.STRING, + number=11, + ) + scaling = proto.Field( + proto.MESSAGE, + number=12, + message=vendor_settings.RevisionScaling, + ) + vpc_access = proto.Field( + proto.MESSAGE, + number=13, + message=vendor_settings.VpcAccess, + ) + container_concurrency = proto.Field( + proto.INT32, + number=14, + ) + timeout = proto.Field( + proto.MESSAGE, + number=15, + message=duration_pb2.Duration, + ) + service_account = proto.Field( + proto.STRING, + number=16, + ) + containers = proto.RepeatedField( + proto.MESSAGE, + number=17, + message=k8s_min.Container, + ) + volumes = proto.RepeatedField( + proto.MESSAGE, + number=18, + message=k8s_min.Volume, + ) + confidential = proto.Field( + proto.BOOL, + number=19, + ) + execution_environment = proto.Field( + proto.ENUM, + number=20, + enum=vendor_settings.ExecutionEnvironment, + ) + encryption_key = proto.Field( + proto.STRING, + number=21, + ) + reconciling = proto.Field( + proto.BOOL, + number=30, + ) + conditions = proto.RepeatedField( + proto.MESSAGE, + number=31, + message=condition.Condition, + ) + observed_generation = proto.Field( + proto.INT64, + number=32, + ) + log_uri = proto.Field( + proto.STRING, + number=33, + ) + etag = proto.Field( + proto.STRING, + number=99, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/revision_template.py b/owl-bot-staging/v2/google/cloud/run_v2/types/revision_template.py new file mode 100644 index 0000000..9480752 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/types/revision_template.py @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.run_v2.types import k8s_min +from google.cloud.run_v2.types import vendor_settings +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.run.v2', + manifest={ + 'RevisionTemplate', + }, +) + + +class RevisionTemplate(proto.Message): + r"""RevisionTemplate describes the data a revision should have + when created from a template. + + Attributes: + revision (str): + The unique name for the revision. If this + field is omitted, it will be automatically + generated based on the Service name. + labels (Mapping[str, str]): + KRM-style labels for the resource. + annotations (Mapping[str, str]): + KRM-style annotations for the resource. + scaling (google.cloud.run_v2.types.RevisionScaling): + Scaling settings for this Revision. + vpc_access (google.cloud.run_v2.types.VpcAccess): + VPC Access configuration to use for this + Revision. For more information, visit + https://cloud.google.com/run/docs/configuring/connecting-vpc. + container_concurrency (int): + Sets the maximum number of requests that each + serving instance can receive. + timeout (google.protobuf.duration_pb2.Duration): + Max allowed time for an instance to respond + to a request. + service_account (str): + Email address of the IAM service account + associated with the revision of the service. The + service account represents the identity of the + running revision, and determines what + permissions the revision has. If not provided, + the revision will use the project's default + service account. + containers (Sequence[google.cloud.run_v2.types.Container]): + Holds the single container that defines the + unit of execution for this Revision. + volumes (Sequence[google.cloud.run_v2.types.Volume]): + A list of Volumes to make available to + containers. + confidential (bool): + Enables Confidential Cloud Run in Revisions + created using this template. + execution_environment (google.cloud.run_v2.types.ExecutionEnvironment): + The sandbox environment to host this + Revision. + encryption_key (str): + A reference to a customer managed encryption + key (CMEK) to use to encrypt this container + image. For more information, go to + https://cloud.google.com/run/docs/securing/using-cmek + """ + + revision = proto.Field( + proto.STRING, + number=1, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + annotations = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + scaling = proto.Field( + proto.MESSAGE, + number=4, + message=vendor_settings.RevisionScaling, + ) + vpc_access = proto.Field( + proto.MESSAGE, + number=6, + message=vendor_settings.VpcAccess, + ) + container_concurrency = proto.Field( + proto.INT32, + number=7, + ) + timeout = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + service_account = proto.Field( + proto.STRING, + number=9, + ) + containers = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=k8s_min.Container, + ) + volumes = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=k8s_min.Volume, + ) + confidential = proto.Field( + proto.BOOL, + number=12, + ) + execution_environment = proto.Field( + proto.ENUM, + number=13, + enum=vendor_settings.ExecutionEnvironment, + ) + encryption_key = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/service.py b/owl-bot-staging/v2/google/cloud/run_v2/types/service.py new file mode 100644 index 0000000..a5c574e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/types/service.py @@ -0,0 +1,521 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.api import launch_stage_pb2 # type: ignore +from google.cloud.run_v2.types import condition +from google.cloud.run_v2.types import revision_template +from google.cloud.run_v2.types import traffic_target +from google.cloud.run_v2.types import vendor_settings +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.run.v2', + manifest={ + 'CreateServiceRequest', + 'UpdateServiceRequest', + 'ListServicesRequest', + 'ListServicesResponse', + 'GetServiceRequest', + 'DeleteServiceRequest', + 'Service', + }, +) + + +class CreateServiceRequest(proto.Message): + r"""Request message for creating a Service. + + Attributes: + parent (str): + Required. The location and project in which + this service should be created. Format: + projects/{projectnumber}/locations/{location} + service (google.cloud.run_v2.types.Service): + Required. The Service instance to create. + service_id (str): + Required. The unique identifier for the Service. The name of + the service becomes {parent}/services/{service_id}. + validate_only (bool): + Indicates that the request should be + validated and default values populated, without + persisting the request or creating any + resources. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + service = proto.Field( + proto.MESSAGE, + number=2, + message='Service', + ) + service_id = proto.Field( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateServiceRequest(proto.Message): + r"""Request message for updating a service. + + Attributes: + service (google.cloud.run_v2.types.Service): + Required. The Service to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + validate_only (bool): + Indicates that the request should be + validated and default values populated, without + persisting the request or updating any + resources. + allow_missing (bool): + If set to true, and if the Service does not + exist, it will create a new one. Caller must + have both create and update permissions for this + call if this is set to true. + """ + + service = proto.Field( + proto.MESSAGE, + number=1, + message='Service', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only = proto.Field( + proto.BOOL, + number=3, + ) + allow_missing = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListServicesRequest(proto.Message): + r"""Request message for retrieving a list of Services. + + Attributes: + parent (str): + Required. The location and project to list + resources on. Location must be a valid GCP + region, and may not be the "-" wildcard. Format: + projects/{projectnumber}/locations/{location} + page_size (int): + Maximum number of Services to return in this + call. + page_token (str): + A page token received from a previous call to + ListServices. All other parameters must match. + show_deleted (bool): + If true, returns deleted (but unexpired) + resources along with active ones. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + show_deleted = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListServicesResponse(proto.Message): + r"""Response message containing a list of Services. + + Attributes: + services (Sequence[google.cloud.run_v2.types.Service]): + The resulting list of Services. + next_page_token (str): + A token indicating there are more items than page_size. Use + it in the next ListServices request to continue. + """ + + @property + def raw_page(self): + return self + + services = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Service', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetServiceRequest(proto.Message): + r"""Request message for obtaining a Service by its full name. + + Attributes: + name (str): + Required. The full name of the Service. + Format: + projects/{projectnumber}/locations/{location}/services/{service} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteServiceRequest(proto.Message): + r"""Request message to delete a Service by its full name. + + Attributes: + name (str): + Required. The full name of the Service. + Format: + projects/{projectnumber}/locations/{location}/services/{service} + validate_only (bool): + Indicates that the request should be + validated without actually deleting any + resources. + etag (str): + A system-generated fingerprint for this + version of the resource. May be used to detect + modification conflict during updates. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + validate_only = proto.Field( + proto.BOOL, + number=2, + ) + etag = proto.Field( + proto.STRING, + number=3, + ) + + +class Service(proto.Message): + r"""Service acts as a top-level container that manages a set of + configurations and revision templates which implement a network + service. Service exists to provide a singular abstraction which + can be access controlled, reasoned about, and which encapsulates + software lifecycle decisions such as rollout policy and team + resource ownership. + + Attributes: + name (str): + The fully qualified name of this Service. In + CreateServiceRequest, this field is ignored, and instead + composed from CreateServiceRequest.parent and + CreateServiceRequest.service_id. + + Format: + projects/{project}/locations/{location}/services/{service_id} + description (str): + User-provided description of the Service. + This field currently has a 512-character limit. + uid (str): + Output only. Server assigned unique + identifier for the trigger. The value is a UUID4 + string and guaranteed to remain unchanged until + the resource is deleted. + generation (int): + Output only. A number that monotonically + increases every time the user modifies the + desired state. + labels (Mapping[str, str]): + Map of string keys and values that can be + used to organize and categorize objects. + User-provided labels are shared with Google's + billing system, so they can be used to filter, + or break down billing charges by team, + component, environment, state, etc. For more + information, visit + https://cloud.google.com/resource-manager/docs/creating-managing-labels + or + https://cloud.google.com/run/docs/configuring/labels + Cloud Run will populate some labels with + 'run.googleapis.com' or 'serving.knative.dev' + namespaces. Those labels are read-only, and user + changes will not be preserved. + annotations (Mapping[str, str]): + Unstructured key value map that may be set by + external tools to store and arbitrary metadata. + They are not queryable and should be preserved + when modifying objects. Cloud Run will populate + some annotations using 'run.googleapis.com' or + 'serving.knative.dev' namespaces. This field + follows Kubernetes annotations' namespacing, + limits, and rules. More info: + https://kubernetes.io/docs/user-guide/annotations + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last-modified time. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The deletion time. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. For a deleted resource, the time + after which it will be permamently deleted. + creator (str): + Output only. Email address of the + authenticated creator. + last_modifier (str): + Output only. Email address of the last + authenticated modifier. + client (str): + Arbitrary identifier for the API client. + client_version (str): + Arbitrary version identifier for the API + client. + ingress (google.cloud.run_v2.types.IngressTraffic): + Provides the ingress settings for this Service. On output, + returns the currently observed ingress settings, or + INGRESS_TRAFFIC_UNSPECIFIED if no revision is active. + launch_stage (google.api.launch_stage_pb2.LaunchStage): + The launch stage as defined by `Google Cloud Platform Launch + Stages `__. + Cloud Run supports ``ALPHA``, ``BETA``, and ``GA``. If no + value is specified, GA is assumed. + binary_authorization (google.cloud.run_v2.types.BinaryAuthorization): + Settings for the Binary Authorization + feature. + template (google.cloud.run_v2.types.RevisionTemplate): + Required. The template used to create + revisions for this Service. + traffic (Sequence[google.cloud.run_v2.types.TrafficTarget]): + Specifies how to distribute traffic over a collection of + Revisions belonging to the Service. If traffic is empty or + not provided, defaults to 100% traffic to the latest + ``Ready`` Revision. + observed_generation (int): + Output only. The generation of this Service currently + serving traffic. See comments in ``reconciling`` for + additional information on reconciliation process in Cloud + Run. + terminal_condition (google.cloud.run_v2.types.Condition): + Output only. The Condition of this Service, containing its + readiness status, and detailed error information in case it + did not reach a serving state. See comments in + ``reconciling`` for additional information on reconciliation + process in Cloud Run. + conditions (Sequence[google.cloud.run_v2.types.Condition]): + Output only. The Conditions of all other associated + sub-resources. They contain additional diagnostics + information in case the Service does not reach its Serving + state. See comments in ``reconciling`` for additional + information on reconciliation process in Cloud Run. + latest_ready_revision (str): + Output only. Name of the latest revision that is serving + traffic. See comments in ``reconciling`` for additional + information on reconciliation process in Cloud Run. + latest_created_revision (str): + Output only. Name of the last created revision. See comments + in ``reconciling`` for additional information on + reconciliation process in Cloud Run. + traffic_statuses (Sequence[google.cloud.run_v2.types.TrafficTargetStatus]): + Output only. Detailed status information for corresponding + traffic targets. See comments in ``reconciling`` for + additional information on reconciliation process in Cloud + Run. + uri (str): + Output only. The main URI in which this + Service is serving traffic. + reconciling (bool): + Output only. Returns true if the Service is currently being + acted upon by the system to bring it into the desired state. + + When a new Service is created, or an existing one is + updated, Cloud Run will asynchronously perform all necessary + steps to bring the Service to the desired serving state. + This process is called reconciliation. While reconciliation + is in process, ``observed_generation``, + ``latest_ready_revison``, ``traffic_statuses``, and ``uri`` + will have transient values that might mismatch the intended + state: Once reconciliation is over (and this field is + false), there are two possible outcomes: reconciliation + succeeded and the serving state matches the Service, or + there was an error, and reconciliation failed. This state + can be found in ``terminal_condition.state``. + + If reconciliation succeeded, the following fields will + match: ``traffic`` and ``traffic_statuses``, + ``observed_generation`` and ``generation``, + ``latest_ready_revision`` and ``latest_created_revision``. + + If reconciliation failed, ``traffic_statuses``, + ``observed_generation``, and ``latest_ready_revision`` will + have the state of the last serving revision, or empty for + newly created Services. Additional information on the + failure can be found in ``terminal_condition`` and + ``conditions``. + etag (str): + Output only. A system-generated fingerprint + for this version of the resource. May be used to + detect modification conflict during updates. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + uid = proto.Field( + proto.STRING, + number=3, + ) + generation = proto.Field( + proto.INT64, + number=4, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + annotations = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + delete_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + expire_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + creator = proto.Field( + proto.STRING, + number=11, + ) + last_modifier = proto.Field( + proto.STRING, + number=12, + ) + client = proto.Field( + proto.STRING, + number=13, + ) + client_version = proto.Field( + proto.STRING, + number=14, + ) + ingress = proto.Field( + proto.ENUM, + number=15, + enum=vendor_settings.IngressTraffic, + ) + launch_stage = proto.Field( + proto.ENUM, + number=16, + enum=launch_stage_pb2.LaunchStage, + ) + binary_authorization = proto.Field( + proto.MESSAGE, + number=17, + message=vendor_settings.BinaryAuthorization, + ) + template = proto.Field( + proto.MESSAGE, + number=18, + message=revision_template.RevisionTemplate, + ) + traffic = proto.RepeatedField( + proto.MESSAGE, + number=19, + message=traffic_target.TrafficTarget, + ) + observed_generation = proto.Field( + proto.INT64, + number=30, + ) + terminal_condition = proto.Field( + proto.MESSAGE, + number=31, + message=condition.Condition, + ) + conditions = proto.RepeatedField( + proto.MESSAGE, + number=32, + message=condition.Condition, + ) + latest_ready_revision = proto.Field( + proto.STRING, + number=33, + ) + latest_created_revision = proto.Field( + proto.STRING, + number=34, + ) + traffic_statuses = proto.RepeatedField( + proto.MESSAGE, + number=35, + message=traffic_target.TrafficTargetStatus, + ) + uri = proto.Field( + proto.STRING, + number=36, + ) + reconciling = proto.Field( + proto.BOOL, + number=98, + ) + etag = proto.Field( + proto.STRING, + number=99, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/traffic_target.py b/owl-bot-staging/v2/google/cloud/run_v2/types/traffic_target.py new file mode 100644 index 0000000..875a209 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/types/traffic_target.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.run.v2', + manifest={ + 'TrafficTargetAllocationType', + 'TrafficTarget', + 'TrafficTargetStatus', + }, +) + + +class TrafficTargetAllocationType(proto.Enum): + r"""The type of instance allocation.""" + TRAFFIC_TARGET_ALLOCATION_TYPE_UNSPECIFIED = 0 + TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST = 1 + TRAFFIC_TARGET_ALLOCATION_TYPE_REVISION = 2 + + +class TrafficTarget(proto.Message): + r"""Holds a single traffic routing entry for the Service. + Allocations can be done to a specific Revision name, or pointing + to the latest Ready Revision. + + Attributes: + type_ (google.cloud.run_v2.types.TrafficTargetAllocationType): + The allocation type for this traffic target. + revision (str): + Revision to which to send this portion of + traffic, if traffic allocation is by revision. + percent (int): + Specifies percent of the traffic to this + Revision. This defaults to zero if unspecified. + tag (str): + Indicates a string to be part of the URI to + exclusively reference this target. + """ + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='TrafficTargetAllocationType', + ) + revision = proto.Field( + proto.STRING, + number=2, + ) + percent = proto.Field( + proto.INT32, + number=3, + ) + tag = proto.Field( + proto.STRING, + number=4, + ) + + +class TrafficTargetStatus(proto.Message): + r"""Represents the observed state of a single ``TrafficTarget`` entry. + + Attributes: + type_ (google.cloud.run_v2.types.TrafficTargetAllocationType): + The allocation type for this traffic target. + revision (str): + Revision to which this traffic is sent. + percent (int): + Specifies percent of the traffic to this + Revision. + tag (str): + Indicates the string used in the URI to + exclusively reference this target. + uri (str): + Displays the target URI. + """ + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='TrafficTargetAllocationType', + ) + revision = proto.Field( + proto.STRING, + number=2, + ) + percent = proto.Field( + proto.INT32, + number=3, + ) + tag = proto.Field( + proto.STRING, + number=4, + ) + uri = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/vendor_settings.py b/owl-bot-staging/v2/google/cloud/run_v2/types/vendor_settings.py new file mode 100644 index 0000000..17a9a80 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/run_v2/types/vendor_settings.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.run.v2', + manifest={ + 'IngressTraffic', + 'ExecutionEnvironment', + 'VpcAccess', + 'BinaryAuthorization', + 'RevisionScaling', + }, +) + + +class IngressTraffic(proto.Enum): + r"""Allowed ingress traffic for the Container.""" + INGRESS_TRAFFIC_UNSPECIFIED = 0 + INGRESS_TRAFFIC_ALL = 1 + INGRESS_TRAFFIC_INTERNAL_ONLY = 2 + INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER = 3 + + +class ExecutionEnvironment(proto.Enum): + r"""Alternatives for execution environments.""" + EXECUTION_ENVIRONMENT_UNSPECIFIED = 0 + EXECUTION_ENVIRONMENT_DEFAULT = 1 + EXECUTION_ENVIRONMENT_GEN2 = 2 + + +class VpcAccess(proto.Message): + r"""VPC Access settings. For more information on creating a VPC + Connector, visit + https://cloud.google.com/vpc/docs/configure-serverless-vpc-access + For information on how to configure Cloud Run with an existing + VPC Connector, visit + https://cloud.google.com/run/docs/configuring/connecting-vpc + + Attributes: + connector (str): + VPC Access connector name. + Format: + projects/{project}/locations/{location}/connectors/{connector} + egress (google.cloud.run_v2.types.VpcAccess.VpcEgress): + Traffic VPC egress settings. + """ + class VpcEgress(proto.Enum): + r"""Egress options for VPC access.""" + VPC_EGRESS_UNSPECIFIED = 0 + ALL_TRAFFIC = 1 + PRIVATE_RANGES_ONLY = 2 + + connector = proto.Field( + proto.STRING, + number=1, + ) + egress = proto.Field( + proto.ENUM, + number=2, + enum=VpcEgress, + ) + + +class BinaryAuthorization(proto.Message): + r"""Settings for Binary Authorization feature. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + use_default (bool): + If True, indicates to use the default + project's binary authorization policy. If False, + binary authorization will be disabled. + + This field is a member of `oneof`_ ``binauthz_method``. + breakglass_justification (str): + If present, indicates to use Breakglass using this + justification. If use_default is False, then it must be + empty. For more information on breakglass, see + https://cloud.google.com/binary-authorization/docs/using-breakglass + """ + + use_default = proto.Field( + proto.BOOL, + number=1, + oneof='binauthz_method', + ) + breakglass_justification = proto.Field( + proto.STRING, + number=2, + ) + + +class RevisionScaling(proto.Message): + r"""Settings for revision-level scaling settings. + + Attributes: + min_instance_count (int): + Minimum number of serving instances that this + resource should have. + max_instance_count (int): + Maximum number of serving instances that this + resource should have. + """ + + min_instance_count = proto.Field( + proto.INT32, + number=1, + ) + max_instance_count = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py new file mode 100644 index 0000000..d2f4263 --- /dev/null +++ b/owl-bot-staging/v2/noxfile.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", +] + +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") + +BLACK_VERSION = "black==19.10b0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.9" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +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/run_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-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=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_async.py new file mode 100644 index 0000000..27d3195 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRevision +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Revisions_DeleteRevision_async] +from google.cloud import run_v2 + + +async def sample_delete_revision(): + # Create a client + client = run_v2.RevisionsAsyncClient() + + # Initialize request argument(s) + request = run_v2.DeleteRevisionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_revision(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Revisions_DeleteRevision_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync.py new file mode 100644 index 0000000..c5196ac --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRevision +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Revisions_DeleteRevision_sync] +from google.cloud import run_v2 + + +def sample_delete_revision(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.DeleteRevisionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_revision(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Revisions_DeleteRevision_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_async.py new file mode 100644 index 0000000..c4c2433 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRevision +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Revisions_GetRevision_async] +from google.cloud import run_v2 + + +async def sample_get_revision(): + # Create a client + client = run_v2.RevisionsAsyncClient() + + # Initialize request argument(s) + request = run_v2.GetRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_revision(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Revisions_GetRevision_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_sync.py new file mode 100644 index 0000000..81c70c9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRevision +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Revisions_GetRevision_sync] +from google.cloud import run_v2 + + +def sample_get_revision(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.GetRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_revision(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Revisions_GetRevision_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_async.py new file mode 100644 index 0000000..b59fa1f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRevisions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Revisions_ListRevisions_async] +from google.cloud import run_v2 + + +async def sample_list_revisions(): + # Create a client + client = run_v2.RevisionsAsyncClient() + + # Initialize request argument(s) + request = run_v2.ListRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END run_v2_generated_Revisions_ListRevisions_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync.py new file mode 100644 index 0000000..e76f3f3 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRevisions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Revisions_ListRevisions_sync] +from google.cloud import run_v2 + + +def sample_list_revisions(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.ListRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END run_v2_generated_Revisions_ListRevisions_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_async.py new file mode 100644 index 0000000..9d067f2 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_CreateService_async] +from google.cloud import run_v2 + + +async def sample_create_service(): + # Create a client + client = run_v2.ServicesAsyncClient() + + # Initialize request argument(s) + request = run_v2.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_CreateService_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_sync.py new file mode 100644 index 0000000..88a1cf3 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_CreateService_sync] +from google.cloud import run_v2 + + +def sample_create_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_CreateService_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_async.py new file mode 100644 index 0000000..6ae4a76 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_DeleteService_async] +from google.cloud import run_v2 + + +async def sample_delete_service(): + # Create a client + client = run_v2.ServicesAsyncClient() + + # Initialize request argument(s) + request = run_v2.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_DeleteService_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_sync.py new file mode 100644 index 0000000..6cde79a --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_DeleteService_sync] +from google.cloud import run_v2 + + +def sample_delete_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_DeleteService_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_async.py new file mode 100644 index 0000000..a492b45 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_GetIamPolicy_async] +from google.cloud import run_v2 + + +async def sample_get_iam_policy(): + # Create a client + client = run_v2.ServicesAsyncClient() + + # Initialize request argument(s) + request = run_v2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_GetIamPolicy_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync.py new file mode 100644 index 0000000..b30e6fb --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_GetIamPolicy_sync] +from google.cloud import run_v2 + + +def sample_get_iam_policy(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_GetIamPolicy_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_async.py new file mode 100644 index 0000000..4b4a653 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_GetService_async] +from google.cloud import run_v2 + + +async def sample_get_service(): + # Create a client + client = run_v2.ServicesAsyncClient() + + # Initialize request argument(s) + request = run_v2.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_GetService_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_sync.py new file mode 100644 index 0000000..b04592b --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_GetService_sync] +from google.cloud import run_v2 + + +def sample_get_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_GetService_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_async.py new file mode 100644 index 0000000..bd2a32c --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServices +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_ListServices_async] +from google.cloud import run_v2 + + +async def sample_list_services(): + # Create a client + client = run_v2.ServicesAsyncClient() + + # Initialize request argument(s) + request = run_v2.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END run_v2_generated_Services_ListServices_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_sync.py new file mode 100644 index 0000000..fc68512 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServices +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_ListServices_sync] +from google.cloud import run_v2 + + +def sample_list_services(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END run_v2_generated_Services_ListServices_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_async.py new file mode 100644 index 0000000..a39cadd --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_SetIamPolicy_async] +from google.cloud import run_v2 + + +async def sample_set_iam_policy(): + # Create a client + client = run_v2.ServicesAsyncClient() + + # Initialize request argument(s) + request = run_v2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_SetIamPolicy_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync.py new file mode 100644 index 0000000..fac34da --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_SetIamPolicy_sync] +from google.cloud import run_v2 + + +def sample_set_iam_policy(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_SetIamPolicy_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_async.py new file mode 100644 index 0000000..74ee78f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_TestIamPermissions_async] +from google.cloud import run_v2 + + +async def sample_test_iam_permissions(): + # Create a client + client = run_v2.ServicesAsyncClient() + + # Initialize request argument(s) + request = run_v2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value_1', 'permissions_value_2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_TestIamPermissions_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync.py new file mode 100644 index 0000000..a33107a --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_TestIamPermissions_sync] +from google.cloud import run_v2 + + +def sample_test_iam_permissions(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value_1', 'permissions_value_2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_TestIamPermissions_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_async.py new file mode 100644 index 0000000..41d52f4 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_UpdateService_async] +from google.cloud import run_v2 + + +async def sample_update_service(): + # Create a client + client = run_v2.ServicesAsyncClient() + + # Initialize request argument(s) + request = run_v2.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_UpdateService_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_sync.py new file mode 100644 index 0000000..ccce2fc --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Services_UpdateService_sync] +from google.cloud import run_v2 + + +def sample_update_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_UpdateService_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_run_v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_run_v2.json new file mode 100644 index 0000000..240cdb5 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_run_v2.json @@ -0,0 +1,983 @@ +{ + "snippets": [ + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Revisions" + }, + "shortName": "DeleteRevision" + } + }, + "file": "run_v2_generated_revisions_delete_revision_async.py", + "regionTag": "run_v2_generated_Revisions_DeleteRevision_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Revisions" + }, + "shortName": "DeleteRevision" + } + }, + "file": "run_v2_generated_revisions_delete_revision_sync.py", + "regionTag": "run_v2_generated_Revisions_DeleteRevision_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Revisions" + }, + "shortName": "GetRevision" + } + }, + "file": "run_v2_generated_revisions_get_revision_async.py", + "regionTag": "run_v2_generated_Revisions_GetRevision_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Revisions" + }, + "shortName": "GetRevision" + } + }, + "file": "run_v2_generated_revisions_get_revision_sync.py", + "regionTag": "run_v2_generated_Revisions_GetRevision_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Revisions" + }, + "shortName": "ListRevisions" + } + }, + "file": "run_v2_generated_revisions_list_revisions_async.py", + "regionTag": "run_v2_generated_Revisions_ListRevisions_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Revisions" + }, + "shortName": "ListRevisions" + } + }, + "file": "run_v2_generated_revisions_list_revisions_sync.py", + "regionTag": "run_v2_generated_Revisions_ListRevisions_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "CreateService" + } + }, + "file": "run_v2_generated_services_create_service_async.py", + "regionTag": "run_v2_generated_Services_CreateService_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "CreateService" + } + }, + "file": "run_v2_generated_services_create_service_sync.py", + "regionTag": "run_v2_generated_Services_CreateService_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "DeleteService" + } + }, + "file": "run_v2_generated_services_delete_service_async.py", + "regionTag": "run_v2_generated_Services_DeleteService_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "DeleteService" + } + }, + "file": "run_v2_generated_services_delete_service_sync.py", + "regionTag": "run_v2_generated_Services_DeleteService_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "GetIamPolicy" + } + }, + "file": "run_v2_generated_services_get_iam_policy_async.py", + "regionTag": "run_v2_generated_Services_GetIamPolicy_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "GetIamPolicy" + } + }, + "file": "run_v2_generated_services_get_iam_policy_sync.py", + "regionTag": "run_v2_generated_Services_GetIamPolicy_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "GetService" + } + }, + "file": "run_v2_generated_services_get_service_async.py", + "regionTag": "run_v2_generated_Services_GetService_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "GetService" + } + }, + "file": "run_v2_generated_services_get_service_sync.py", + "regionTag": "run_v2_generated_Services_GetService_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "ListServices" + } + }, + "file": "run_v2_generated_services_list_services_async.py", + "regionTag": "run_v2_generated_Services_ListServices_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "ListServices" + } + }, + "file": "run_v2_generated_services_list_services_sync.py", + "regionTag": "run_v2_generated_Services_ListServices_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "SetIamPolicy" + } + }, + "file": "run_v2_generated_services_set_iam_policy_async.py", + "regionTag": "run_v2_generated_Services_SetIamPolicy_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "SetIamPolicy" + } + }, + "file": "run_v2_generated_services_set_iam_policy_sync.py", + "regionTag": "run_v2_generated_Services_SetIamPolicy_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "TestIamPermissions" + } + }, + "file": "run_v2_generated_services_test_iam_permissions_async.py", + "regionTag": "run_v2_generated_Services_TestIamPermissions_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "TestIamPermissions" + } + }, + "file": "run_v2_generated_services_test_iam_permissions_sync.py", + "regionTag": "run_v2_generated_Services_TestIamPermissions_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "UpdateService" + } + }, + "file": "run_v2_generated_services_update_service_async.py", + "regionTag": "run_v2_generated_Services_UpdateService_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "Services" + }, + "shortName": "UpdateService" + } + }, + "file": "run_v2_generated_services_update_service_sync.py", + "regionTag": "run_v2_generated_Services_UpdateService_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + } + ] +} diff --git a/owl-bot-staging/v2/scripts/fixup_run_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_run_v2_keywords.py new file mode 100644 index 0000000..aef6ae6 --- /dev/null +++ b/owl-bot-staging/v2/scripts/fixup_run_v2_keywords.py @@ -0,0 +1,186 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 runCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_service': ('parent', 'service', 'service_id', 'validate_only', ), + 'delete_revision': ('name', 'validate_only', 'etag', ), + 'delete_service': ('name', 'validate_only', 'etag', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_revision': ('name', ), + 'get_service': ('name', ), + 'list_revisions': ('parent', 'page_size', 'page_token', 'show_deleted', ), + 'list_services': ('parent', 'page_size', 'page_token', 'show_deleted', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_service': ('service', 'update_mask', 'validate_only', 'allow_missing', ), + } + + 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=runCallTransformer(), +): + """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 run 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/v2/setup.py b/owl-bot-staging/v2/setup.py new file mode 100644 index 0000000..8393a95 --- /dev/null +++ b/owl-bot-staging/v2/setup.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-run', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-run", + 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.31.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'googleapis-common-protos >= 1.55.0, <2.0.0dev', + 'proto-plus >= 1.19.7', + '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', + 'Programming Language :: Python :: 3.10', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v2/tests/unit/gapic/run_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/run_v2/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/run_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v2/tests/unit/gapic/run_v2/test_revisions.py b/owl-bot-staging/v2/tests/unit/gapic/run_v2/test_revisions.py new file mode 100644 index 0000000..9a39f9c --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/run_v2/test_revisions.py @@ -0,0 +1,2197 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.run_v2.services.revisions import RevisionsAsyncClient +from google.cloud.run_v2.services.revisions import RevisionsClient +from google.cloud.run_v2.services.revisions import pagers +from google.cloud.run_v2.services.revisions import transports +from google.cloud.run_v2.types import condition +from google.cloud.run_v2.types import k8s_min +from google.cloud.run_v2.types import revision +from google.cloud.run_v2.types import vendor_settings +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RevisionsClient._get_default_mtls_endpoint(None) is None + assert RevisionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RevisionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RevisionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RevisionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RevisionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RevisionsClient, "grpc"), + (RevisionsAsyncClient, "grpc_asyncio"), +]) +def test_revisions_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'run.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RevisionsGrpcTransport, "grpc"), + (transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_revisions_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RevisionsClient, "grpc"), + (RevisionsAsyncClient, "grpc_asyncio"), +]) +def test_revisions_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'run.googleapis.com:443' + ) + + +def test_revisions_client_get_transport_class(): + transport = RevisionsClient.get_transport_class() + available_transports = [ + transports.RevisionsGrpcTransport, + ] + assert transport in available_transports + + transport = RevisionsClient.get_transport_class("grpc") + assert transport == transports.RevisionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RevisionsClient, transports.RevisionsGrpcTransport, "grpc"), + (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(RevisionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsClient)) +@mock.patch.object(RevisionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsAsyncClient)) +def test_revisions_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(RevisionsClient, '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(RevisionsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RevisionsClient, transports.RevisionsGrpcTransport, "grpc", "true"), + (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RevisionsClient, transports.RevisionsGrpcTransport, "grpc", "false"), + (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(RevisionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsClient)) +@mock.patch.object(RevisionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_revisions_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + RevisionsClient, RevisionsAsyncClient +]) +@mock.patch.object(RevisionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsClient)) +@mock.patch.object(RevisionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsAsyncClient)) +def test_revisions_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RevisionsClient, transports.RevisionsGrpcTransport, "grpc"), + (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_revisions_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RevisionsClient, transports.RevisionsGrpcTransport, "grpc", grpc_helpers), + (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_revisions_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_revisions_client_client_options_from_dict(): + with mock.patch('google.cloud.run_v2.services.revisions.transports.RevisionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RevisionsClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RevisionsClient, transports.RevisionsGrpcTransport, "grpc", grpc_helpers), + (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_revisions_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "run.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="run.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + revision.GetRevisionRequest, + dict, +]) +def test_get_revision(request_type, transport: str = 'grpc'): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = revision.Revision( + name='name_value', + uid='uid_value', + generation=1068, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service='service_value', + container_concurrency=2253, + service_account='service_account_value', + confidential=True, + execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_DEFAULT, + encryption_key='encryption_key_value', + reconciling=True, + observed_generation=2021, + log_uri='log_uri_value', + etag='etag_value', + ) + response = client.get_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == revision.GetRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, revision.Revision) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.generation == 1068 + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.service == 'service_value' + assert response.container_concurrency == 2253 + assert response.service_account == 'service_account_value' + assert response.confidential is True + assert response.execution_environment == vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_DEFAULT + assert response.encryption_key == 'encryption_key_value' + assert response.reconciling is True + assert response.observed_generation == 2021 + assert response.log_uri == 'log_uri_value' + assert response.etag == 'etag_value' + + +def test_get_revision_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + client.get_revision() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == revision.GetRevisionRequest() + +@pytest.mark.asyncio +async def test_get_revision_async(transport: str = 'grpc_asyncio', request_type=revision.GetRevisionRequest): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(revision.Revision( + name='name_value', + uid='uid_value', + generation=1068, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service='service_value', + container_concurrency=2253, + service_account='service_account_value', + confidential=True, + execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_DEFAULT, + encryption_key='encryption_key_value', + reconciling=True, + observed_generation=2021, + log_uri='log_uri_value', + etag='etag_value', + )) + response = await client.get_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == revision.GetRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, revision.Revision) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.generation == 1068 + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.service == 'service_value' + assert response.container_concurrency == 2253 + assert response.service_account == 'service_account_value' + assert response.confidential is True + assert response.execution_environment == vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_DEFAULT + assert response.encryption_key == 'encryption_key_value' + assert response.reconciling is True + assert response.observed_generation == 2021 + assert response.log_uri == 'log_uri_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_revision_async_from_dict(): + await test_get_revision_async(request_type=dict) + + +def test_get_revision_field_headers(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = revision.GetRevisionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + call.return_value = revision.Revision() + client.get_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_revision_field_headers_async(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = revision.GetRevisionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(revision.Revision()) + await client.get_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_revision_flattened(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = revision.Revision() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_revision( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_revision_flattened_error(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_revision( + revision.GetRevisionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_revision_flattened_async(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = revision.Revision() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(revision.Revision()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_revision( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_revision_flattened_error_async(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_revision( + revision.GetRevisionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + revision.ListRevisionsRequest, + dict, +]) +def test_list_revisions(request_type, transport: str = 'grpc'): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = revision.ListRevisionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == revision.ListRevisionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRevisionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_revisions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + client.list_revisions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == revision.ListRevisionsRequest() + +@pytest.mark.asyncio +async def test_list_revisions_async(transport: str = 'grpc_asyncio', request_type=revision.ListRevisionsRequest): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(revision.ListRevisionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == revision.ListRevisionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRevisionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_revisions_async_from_dict(): + await test_list_revisions_async(request_type=dict) + + +def test_list_revisions_field_headers(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = revision.ListRevisionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + call.return_value = revision.ListRevisionsResponse() + client.list_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_revisions_field_headers_async(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = revision.ListRevisionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(revision.ListRevisionsResponse()) + await client.list_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_revisions_flattened(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = revision.ListRevisionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_revisions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_revisions_flattened_error(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_revisions( + revision.ListRevisionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_revisions_flattened_async(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = revision.ListRevisionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(revision.ListRevisionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_revisions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_revisions_flattened_error_async(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_revisions( + revision.ListRevisionsRequest(), + parent='parent_value', + ) + + +def test_list_revisions_pager(transport_name: str = "grpc"): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + revision.Revision(), + revision.Revision(), + ], + next_page_token='abc', + ), + revision.ListRevisionsResponse( + revisions=[], + next_page_token='def', + ), + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + ], + next_page_token='ghi', + ), + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + revision.Revision(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_revisions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, revision.Revision) + for i in results) +def test_list_revisions_pages(transport_name: str = "grpc"): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + revision.Revision(), + revision.Revision(), + ], + next_page_token='abc', + ), + revision.ListRevisionsResponse( + revisions=[], + next_page_token='def', + ), + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + ], + next_page_token='ghi', + ), + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + revision.Revision(), + ], + ), + RuntimeError, + ) + pages = list(client.list_revisions(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_revisions_async_pager(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + revision.Revision(), + revision.Revision(), + ], + next_page_token='abc', + ), + revision.ListRevisionsResponse( + revisions=[], + next_page_token='def', + ), + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + ], + next_page_token='ghi', + ), + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + revision.Revision(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_revisions(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, revision.Revision) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_revisions_async_pages(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + revision.Revision(), + revision.Revision(), + ], + next_page_token='abc', + ), + revision.ListRevisionsResponse( + revisions=[], + next_page_token='def', + ), + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + ], + next_page_token='ghi', + ), + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + revision.Revision(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_revisions(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + revision.DeleteRevisionRequest, + dict, +]) +def test_delete_revision(request_type, transport: str = 'grpc'): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == revision.DeleteRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_revision_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RevisionsClient( + 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_revision), + '__call__') as call: + client.delete_revision() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == revision.DeleteRevisionRequest() + +@pytest.mark.asyncio +async def test_delete_revision_async(transport: str = 'grpc_asyncio', request_type=revision.DeleteRevisionRequest): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == revision.DeleteRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_revision_async_from_dict(): + await test_delete_revision_async(request_type=dict) + + +def test_delete_revision_field_headers(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = revision.DeleteRevisionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_revision), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_revision_field_headers_async(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = revision.DeleteRevisionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_revision), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_revision_flattened(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_revision( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_revision_flattened_error(): + client = RevisionsClient( + 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_revision( + revision.DeleteRevisionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_revision_flattened_async(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_revision( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_revision_flattened_error_async(): + client = RevisionsAsyncClient( + 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_revision( + revision.DeleteRevisionRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RevisionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RevisionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RevisionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RevisionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RevisionsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RevisionsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RevisionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RevisionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RevisionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RevisionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RevisionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RevisionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RevisionsGrpcTransport, + transports.RevisionsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", +]) +def test_transport_kind(transport_name): + transport = RevisionsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RevisionsGrpcTransport, + ) + +def test_revisions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RevisionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_revisions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.run_v2.services.revisions.transports.RevisionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RevisionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_revision', + 'list_revisions', + 'delete_revision', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_revisions_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.run_v2.services.revisions.transports.RevisionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RevisionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_revisions_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.run_v2.services.revisions.transports.RevisionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RevisionsTransport() + adc.assert_called_once() + + +def test_revisions_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) + RevisionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RevisionsGrpcTransport, + transports.RevisionsGrpcAsyncIOTransport, + ], +) +def test_revisions_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,grpc_helpers", + [ + (transports.RevisionsGrpcTransport, grpc_helpers), + (transports.RevisionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_revisions_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( + "run.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="run.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RevisionsGrpcTransport, transports.RevisionsGrpcAsyncIOTransport]) +def test_revisions_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_revisions_host_no_port(transport_name): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='run.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'run.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_revisions_host_with_port(transport_name): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='run.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'run.googleapis.com:8000' + ) + +def test_revisions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RevisionsGrpcTransport( + 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_revisions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RevisionsGrpcAsyncIOTransport( + 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.RevisionsGrpcTransport, transports.RevisionsGrpcAsyncIOTransport]) +def test_revisions_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.RevisionsGrpcTransport, transports.RevisionsGrpcAsyncIOTransport]) +def test_revisions_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_revisions_grpc_lro_client(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_revisions_grpc_lro_async_client(): + client = RevisionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_connector_path(): + project = "squid" + location = "clam" + connector = "whelk" + expected = "projects/{project}/locations/{location}/connectors/{connector}".format(project=project, location=location, connector=connector, ) + actual = RevisionsClient.connector_path(project, location, connector) + assert expected == actual + + +def test_parse_connector_path(): + expected = { + "project": "octopus", + "location": "oyster", + "connector": "nudibranch", + } + path = RevisionsClient.connector_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_connector_path(path) + assert expected == actual + +def test_crypto_key_path(): + project = "cuttlefish" + location = "mussel" + key_ring = "winkle" + crypto_key = "nautilus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + actual = RevisionsClient.crypto_key_path(project, location, key_ring, crypto_key) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "scallop", + "location": "abalone", + "key_ring": "squid", + "crypto_key": "clam", + } + path = RevisionsClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_crypto_key_path(path) + assert expected == actual + +def test_revision_path(): + project = "whelk" + location = "octopus" + service = "oyster" + revision = "nudibranch" + expected = "projects/{project}/locations/{location}/services/{service}/revisions/{revision}".format(project=project, location=location, service=service, revision=revision, ) + actual = RevisionsClient.revision_path(project, location, service, revision) + assert expected == actual + + +def test_parse_revision_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "service": "winkle", + "revision": "nautilus", + } + path = RevisionsClient.revision_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_revision_path(path) + assert expected == actual + +def test_secret_path(): + project = "scallop" + secret = "abalone" + expected = "projects/{project}/secrets/{secret}".format(project=project, secret=secret, ) + actual = RevisionsClient.secret_path(project, secret) + assert expected == actual + + +def test_parse_secret_path(): + expected = { + "project": "squid", + "secret": "clam", + } + path = RevisionsClient.secret_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_secret_path(path) + assert expected == actual + +def test_secret_version_path(): + project = "whelk" + secret = "octopus" + version = "oyster" + expected = "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) + actual = RevisionsClient.secret_version_path(project, secret, version) + assert expected == actual + + +def test_parse_secret_version_path(): + expected = { + "project": "nudibranch", + "secret": "cuttlefish", + "version": "mussel", + } + path = RevisionsClient.secret_version_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_secret_version_path(path) + assert expected == actual + +def test_service_path(): + project = "winkle" + location = "nautilus" + service = "scallop" + expected = "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) + actual = RevisionsClient.service_path(project, location, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "abalone", + "location": "squid", + "service": "clam", + } + path = RevisionsClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RevisionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = RevisionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = RevisionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = RevisionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RevisionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = RevisionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = RevisionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = RevisionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RevisionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = RevisionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RevisionsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RevisionsTransport, '_prep_wrapped_messages') as prep: + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RevisionsTransport, '_prep_wrapped_messages') as prep: + transport_class = RevisionsClient.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 = RevisionsAsyncClient( + 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 = RevisionsClient( + 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 = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (RevisionsClient, transports.RevisionsGrpcTransport), + (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/run_v2/test_services.py b/owl-bot-staging/v2/tests/unit/gapic/run_v2/test_services.py new file mode 100644 index 0000000..e4ae1cc --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/run_v2/test_services.py @@ -0,0 +1,3218 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.run_v2.services.services import ServicesAsyncClient +from google.cloud.run_v2.services.services import ServicesClient +from google.cloud.run_v2.services.services import pagers +from google.cloud.run_v2.services.services import transports +from google.cloud.run_v2.types import condition +from google.cloud.run_v2.types import k8s_min +from google.cloud.run_v2.types import revision_template +from google.cloud.run_v2.types import service +from google.cloud.run_v2.types import service as gcr_service +from google.cloud.run_v2.types import traffic_target +from google.cloud.run_v2.types import vendor_settings +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +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 + + +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 ServicesClient._get_default_mtls_endpoint(None) is None + assert ServicesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ServicesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ServicesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ServicesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ServicesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServicesClient, "grpc"), + (ServicesAsyncClient, "grpc_asyncio"), +]) +def test_services_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'run.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ServicesGrpcTransport, "grpc"), + (transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_services_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServicesClient, "grpc"), + (ServicesAsyncClient, "grpc_asyncio"), +]) +def test_services_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'run.googleapis.com:443' + ) + + +def test_services_client_get_transport_class(): + transport = ServicesClient.get_transport_class() + available_transports = [ + transports.ServicesGrpcTransport, + ] + assert transport in available_transports + + transport = ServicesClient.get_transport_class("grpc") + assert transport == transports.ServicesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServicesClient, transports.ServicesGrpcTransport, "grpc"), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)) +@mock.patch.object(ServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesAsyncClient)) +def test_services_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(ServicesClient, '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(ServicesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ServicesClient, transports.ServicesGrpcTransport, "grpc", "true"), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ServicesClient, transports.ServicesGrpcTransport, "grpc", "false"), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)) +@mock.patch.object(ServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_services_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + ServicesClient, ServicesAsyncClient +]) +@mock.patch.object(ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)) +@mock.patch.object(ServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesAsyncClient)) +def test_services_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServicesClient, transports.ServicesGrpcTransport, "grpc"), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_services_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServicesClient, transports.ServicesGrpcTransport, "grpc", grpc_helpers), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_services_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_services_client_client_options_from_dict(): + with mock.patch('google.cloud.run_v2.services.services.transports.ServicesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ServicesClient( + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServicesClient, transports.ServicesGrpcTransport, "grpc", grpc_helpers), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_services_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "run.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="run.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + gcr_service.CreateServiceRequest, + dict, +]) +def test_create_service(request_type, transport: str = 'grpc'): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcr_service.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +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 = ServicesClient( + 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] == gcr_service.CreateServiceRequest() + +@pytest.mark.asyncio +async def test_create_service_async(transport: str = 'grpc_asyncio', request_type=gcr_service.CreateServiceRequest): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcr_service.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_service_async_from_dict(): + await test_create_service_async(request_type=dict) + + +def test_create_service_field_headers(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcr_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 = operations_pb2.Operation(name='operations/op') + 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 = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcr_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(operations_pb2.Operation(name='operations/op')) + 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_service( + parent='parent_value', + service=gcr_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] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].service + mock_val = gcr_service.Service(name='name_value') + assert arg == mock_val + arg = args[0].service_id + mock_val = 'service_id_value' + assert arg == mock_val + + +def test_create_service_flattened_error(): + client = ServicesClient( + 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( + gcr_service.CreateServiceRequest(), + parent='parent_value', + service=gcr_service.Service(name='name_value'), + service_id='service_id_value', + ) + +@pytest.mark.asyncio +async def test_create_service_flattened_async(): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_service( + parent='parent_value', + service=gcr_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] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].service + mock_val = gcr_service.Service(name='name_value') + assert arg == mock_val + arg = args[0].service_id + mock_val = 'service_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_service_flattened_error_async(): + client = ServicesAsyncClient( + 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( + gcr_service.CreateServiceRequest(), + parent='parent_value', + service=gcr_service.Service(name='name_value'), + service_id='service_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetServiceRequest, + dict, +]) +def test_get_service(request_type, transport: str = 'grpc'): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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', + description='description_value', + uid='uid_value', + generation=1068, + creator='creator_value', + last_modifier='last_modifier_value', + client='client_value', + client_version='client_version_value', + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + observed_generation=2021, + latest_ready_revision='latest_ready_revision_value', + latest_created_revision='latest_created_revision_value', + uri='uri_value', + reconciling=True, + etag='etag_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] == service.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.uid == 'uid_value' + assert response.generation == 1068 + assert response.creator == 'creator_value' + assert response.last_modifier == 'last_modifier_value' + assert response.client == 'client_value' + assert response.client_version == 'client_version_value' + assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.observed_generation == 2021 + assert response.latest_ready_revision == 'latest_ready_revision_value' + assert response.latest_created_revision == 'latest_created_revision_value' + assert response.uri == 'uri_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + + +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 = ServicesClient( + 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] == service.GetServiceRequest() + +@pytest.mark.asyncio +async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=service.GetServiceRequest): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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', + description='description_value', + uid='uid_value', + generation=1068, + creator='creator_value', + last_modifier='last_modifier_value', + client='client_value', + client_version='client_version_value', + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + observed_generation=2021, + latest_ready_revision='latest_ready_revision_value', + latest_created_revision='latest_created_revision_value', + uri='uri_value', + reconciling=True, + etag='etag_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] == service.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.uid == 'uid_value' + assert response.generation == 1068 + assert response.creator == 'creator_value' + assert response.last_modifier == 'last_modifier_value' + assert response.client == 'client_value' + assert response.client_version == 'client_version_value' + assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.observed_generation == 2021 + assert response.latest_ready_revision == 'latest_ready_revision_value' + assert response.latest_created_revision == 'latest_created_revision_value' + assert response.uri == 'uri_value' + assert response.reconciling is True + assert response.etag == 'etag_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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = ServicesClient( + 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] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_service_flattened_error(): + client = ServicesClient( + 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( + service.GetServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_service_flattened_async(): + client = ServicesAsyncClient( + 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] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_service_flattened_error_async(): + client = ServicesAsyncClient( + 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( + service.GetServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListServicesRequest, + dict, +]) +def test_list_services(request_type, transport: str = 'grpc'): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = 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] == 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_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 = ServicesClient( + 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] == service.ListServicesRequest() + +@pytest.mark.asyncio +async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=service.ListServicesRequest): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(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] == 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = 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 = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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(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 = ServicesClient( + 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 = 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] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_services_flattened_error(): + client = ServicesClient( + 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( + service.ListServicesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_services_flattened_async(): + client = ServicesAsyncClient( + 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 = service.ListServicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(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] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_services_flattened_error_async(): + client = ServicesAsyncClient( + 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( + service.ListServicesRequest(), + parent='parent_value', + ) + + +def test_list_services_pager(transport_name: str = "grpc"): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + service.ListServicesResponse( + services=[], + next_page_token='def', + ), + service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + 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(transport_name: str = "grpc"): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + service.ListServicesResponse( + services=[], + next_page_token='def', + ), + service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + 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 = ServicesAsyncClient( + 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 = ( + service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + service.ListServicesResponse( + services=[], + next_page_token='def', + ), + service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + 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: # pragma: no branch + 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 = ServicesAsyncClient( + 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 = ( + service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + service.ListServicesResponse( + services=[], + next_page_token='def', + ), + service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_services(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + gcr_service.UpdateServiceRequest, + dict, +]) +def test_update_service(request_type, transport: str = 'grpc'): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = operations_pb2.Operation(name='operations/spam') + 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] == gcr_service.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +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 = ServicesClient( + 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] == gcr_service.UpdateServiceRequest() + +@pytest.mark.asyncio +async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=gcr_service.UpdateServiceRequest): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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( + operations_pb2.Operation(name='operations/spam') + ) + 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] == gcr_service.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcr_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 = operations_pb2.Operation(name='operations/op') + 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 = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcr_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(operations_pb2.Operation(name='operations/op')) + 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 = ServicesClient( + 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 = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_service( + service=gcr_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] + arg = args[0].service + mock_val = gcr_service.Service(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_service_flattened_error(): + client = ServicesClient( + 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( + gcr_service.UpdateServiceRequest(), + service=gcr_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 = ServicesAsyncClient( + 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 = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_service( + service=gcr_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] + arg = args[0].service + mock_val = gcr_service.Service(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_service_flattened_error_async(): + client = ServicesAsyncClient( + 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( + gcr_service.UpdateServiceRequest(), + service=gcr_service.Service(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteServiceRequest, + dict, +]) +def test_delete_service(request_type, transport: str = 'grpc'): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +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 = ServicesClient( + 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] == service.DeleteServiceRequest() + +@pytest.mark.asyncio +async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=service.DeleteServiceRequest): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_service_async_from_dict(): + await test_delete_service_async(request_type=dict) + + +def test_delete_service_field_headers(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = operations_pb2.Operation(name='operations/op') + client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_service_field_headers_async(): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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(operations_pb2.Operation(name='operations/op')) + await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_service_flattened(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_service_flattened_error(): + client = ServicesClient( + 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( + service.DeleteServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_service_flattened_async(): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_service_flattened_error_async(): + client = ServicesAsyncClient( + 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( + service.DeleteServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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 = ServicesClient( + 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 = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.get_iam_policy(request={ + 'resource': 'resource_value', + 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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 = ServicesClient( + 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 = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ServicesClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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 = ServicesClient( + 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 = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ServicesClient( + 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.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServicesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServicesClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServicesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServicesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ServicesGrpcTransport, + transports.ServicesGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", +]) +def test_transport_kind(transport_name): + transport = ServicesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServicesGrpcTransport, + ) + +def test_services_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_services_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.run_v2.services.services.transports.ServicesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_service', + 'get_service', + 'list_services', + 'update_service', + 'delete_service', + '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() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_services_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.run_v2.services.services.transports.ServicesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServicesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_services_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.run_v2.services.services.transports.ServicesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServicesTransport() + adc.assert_called_once() + + +def test_services_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) + ServicesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServicesGrpcTransport, + transports.ServicesGrpcAsyncIOTransport, + ], +) +def test_services_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,grpc_helpers", + [ + (transports.ServicesGrpcTransport, grpc_helpers), + (transports.ServicesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_services_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( + "run.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="run.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) +def test_services_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_services_host_no_port(transport_name): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='run.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'run.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_services_host_with_port(transport_name): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='run.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'run.googleapis.com:8000' + ) + +def test_services_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServicesGrpcTransport( + 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_services_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServicesGrpcAsyncIOTransport( + 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.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) +def test_services_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.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) +def test_services_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_services_grpc_lro_client(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_services_grpc_lro_async_client(): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_connector_path(): + project = "squid" + location = "clam" + connector = "whelk" + expected = "projects/{project}/locations/{location}/connectors/{connector}".format(project=project, location=location, connector=connector, ) + actual = ServicesClient.connector_path(project, location, connector) + assert expected == actual + + +def test_parse_connector_path(): + expected = { + "project": "octopus", + "location": "oyster", + "connector": "nudibranch", + } + path = ServicesClient.connector_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_connector_path(path) + assert expected == actual + +def test_crypto_key_path(): + project = "cuttlefish" + location = "mussel" + key_ring = "winkle" + crypto_key = "nautilus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + actual = ServicesClient.crypto_key_path(project, location, key_ring, crypto_key) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "scallop", + "location": "abalone", + "key_ring": "squid", + "crypto_key": "clam", + } + path = ServicesClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_crypto_key_path(path) + assert expected == actual + +def test_revision_path(): + project = "whelk" + location = "octopus" + service = "oyster" + revision = "nudibranch" + expected = "projects/{project}/locations/{location}/services/{service}/revisions/{revision}".format(project=project, location=location, service=service, revision=revision, ) + actual = ServicesClient.revision_path(project, location, service, revision) + assert expected == actual + + +def test_parse_revision_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "service": "winkle", + "revision": "nautilus", + } + path = ServicesClient.revision_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_revision_path(path) + assert expected == actual + +def test_secret_path(): + project = "scallop" + secret = "abalone" + expected = "projects/{project}/secrets/{secret}".format(project=project, secret=secret, ) + actual = ServicesClient.secret_path(project, secret) + assert expected == actual + + +def test_parse_secret_path(): + expected = { + "project": "squid", + "secret": "clam", + } + path = ServicesClient.secret_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_secret_path(path) + assert expected == actual + +def test_secret_version_path(): + project = "whelk" + secret = "octopus" + version = "oyster" + expected = "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) + actual = ServicesClient.secret_version_path(project, secret, version) + assert expected == actual + + +def test_parse_secret_version_path(): + expected = { + "project": "nudibranch", + "secret": "cuttlefish", + "version": "mussel", + } + path = ServicesClient.secret_version_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_secret_version_path(path) + assert expected == actual + +def test_service_path(): + project = "winkle" + location = "nautilus" + service = "scallop" + expected = "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) + actual = ServicesClient.service_path(project, location, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "abalone", + "location": "squid", + "service": "clam", + } + path = ServicesClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ServicesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ServicesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ServicesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ServicesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ServicesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ServicesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ServicesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ServicesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ServicesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ServicesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.ServicesTransport, '_prep_wrapped_messages') as prep: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ServicesTransport, '_prep_wrapped_messages') as prep: + transport_class = ServicesClient.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 = ServicesAsyncClient( + 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 = ServicesClient( + 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (ServicesClient, transports.ServicesGrpcTransport), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) From ec717b96817696a48b0af2b4552344e4df59c633 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 11 Apr 2022 22:55:22 +0000 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../run_v2/services/revisions/async_client.py | 3 +- .../cloud/run_v2/services/revisions/client.py | 3 +- .../services/revisions/transports/base.py | 5 + .../services/revisions/transports/grpc.py | 4 + .../run_v2/services/services/async_client.py | 99 +- .../cloud/run_v2/services/services/client.py | 95 +- .../services/services/transports/base.py | 9 +- .../services/services/transports/grpc.py | 4 + google/cloud/run_v2/types/__init__.py | 8 +- google/cloud/run_v2/types/k8s_min.py | 2 +- google/cloud/run_v2/types/revision.py | 4 +- .../cloud/run_v2/types/revision_template.py | 4 +- google/cloud/run_v2/types/service.py | 4 +- owl-bot-staging/v2/.coveragerc | 17 - owl-bot-staging/v2/.flake8 | 33 - owl-bot-staging/v2/MANIFEST.in | 2 - owl-bot-staging/v2/README.rst | 49 - owl-bot-staging/v2/docs/conf.py | 376 -- owl-bot-staging/v2/docs/index.rst | 7 - owl-bot-staging/v2/docs/run_v2/revisions.rst | 10 - owl-bot-staging/v2/docs/run_v2/services.rst | 7 - owl-bot-staging/v2/docs/run_v2/types.rst | 7 - .../v2/google/cloud/run/__init__.py | 93 - owl-bot-staging/v2/google/cloud/run/py.typed | 2 - .../v2/google/cloud/run_v2/__init__.py | 94 - .../google/cloud/run_v2/gapic_metadata.json | 147 - .../v2/google/cloud/run_v2/py.typed | 2 - .../google/cloud/run_v2/services/__init__.py | 15 - .../run_v2/services/revisions/__init__.py | 22 - .../run_v2/services/revisions/async_client.py | 543 --- .../cloud/run_v2/services/revisions/client.py | 787 ---- .../cloud/run_v2/services/revisions/pagers.py | 139 - .../services/revisions/transports/__init__.py | 33 - .../services/revisions/transports/base.py | 185 - .../services/revisions/transports/grpc.py | 334 -- .../revisions/transports/grpc_asyncio.py | 333 -- .../run_v2/services/services/__init__.py | 22 - .../run_v2/services/services/async_client.py | 1176 ------ .../cloud/run_v2/services/services/client.py | 1405 ------- .../cloud/run_v2/services/services/pagers.py | 139 - .../services/services/transports/__init__.py | 33 - .../services/services/transports/base.py | 270 -- .../services/services/transports/grpc.py | 475 --- .../services/transports/grpc_asyncio.py | 474 --- .../v2/google/cloud/run_v2/types/__init__.py | 98 - .../v2/google/cloud/run_v2/types/condition.py | 214 -- .../v2/google/cloud/run_v2/types/k8s_min.py | 477 --- .../v2/google/cloud/run_v2/types/revision.py | 388 -- .../cloud/run_v2/types/revision_template.py | 145 - .../v2/google/cloud/run_v2/types/service.py | 521 --- .../cloud/run_v2/types/traffic_target.py | 115 - .../cloud/run_v2/types/vendor_settings.py | 131 - owl-bot-staging/v2/mypy.ini | 3 - owl-bot-staging/v2/noxfile.py | 180 - ...nerated_revisions_delete_revision_async.py | 49 - ...enerated_revisions_delete_revision_sync.py | 49 - ..._generated_revisions_get_revision_async.py | 45 - ...2_generated_revisions_get_revision_sync.py | 45 - ...enerated_revisions_list_revisions_async.py | 46 - ...generated_revisions_list_revisions_sync.py | 46 - ...generated_services_create_service_async.py | 50 - ..._generated_services_create_service_sync.py | 50 - ...generated_services_delete_service_async.py | 49 - ..._generated_services_delete_service_sync.py | 49 - ...generated_services_get_iam_policy_async.py | 45 - ..._generated_services_get_iam_policy_sync.py | 45 - ...v2_generated_services_get_service_async.py | 45 - ..._v2_generated_services_get_service_sync.py | 45 - ..._generated_services_list_services_async.py | 46 - ...2_generated_services_list_services_sync.py | 46 - ...generated_services_set_iam_policy_async.py | 45 - ..._generated_services_set_iam_policy_sync.py | 45 - ...ted_services_test_iam_permissions_async.py | 46 - ...ated_services_test_iam_permissions_sync.py | 46 - ...generated_services_update_service_async.py | 48 - ..._generated_services_update_service_sync.py | 48 - .../snippet_metadata_run_v2.json | 983 ----- .../v2/scripts/fixup_run_v2_keywords.py | 186 - owl-bot-staging/v2/setup.py | 60 - owl-bot-staging/v2/tests/__init__.py | 16 - owl-bot-staging/v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../v2/tests/unit/gapic/run_v2/__init__.py | 16 - .../tests/unit/gapic/run_v2/test_revisions.py | 2197 ----------- .../tests/unit/gapic/run_v2/test_services.py | 3218 ----------------- scripts/fixup_run_v2_keywords.py | 2 +- tests/unit/gapic/run_v2/test_revisions.py | 21 + tests/unit/gapic/run_v2/test_services.py | 22 + 88 files changed, 183 insertions(+), 17345 deletions(-) delete mode 100644 owl-bot-staging/v2/.coveragerc delete mode 100644 owl-bot-staging/v2/.flake8 delete mode 100644 owl-bot-staging/v2/MANIFEST.in delete mode 100644 owl-bot-staging/v2/README.rst delete mode 100644 owl-bot-staging/v2/docs/conf.py delete mode 100644 owl-bot-staging/v2/docs/index.rst delete mode 100644 owl-bot-staging/v2/docs/run_v2/revisions.rst delete mode 100644 owl-bot-staging/v2/docs/run_v2/services.rst delete mode 100644 owl-bot-staging/v2/docs/run_v2/types.rst delete mode 100644 owl-bot-staging/v2/google/cloud/run/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/run/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/condition.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/k8s_min.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/revision.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/revision_template.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/service.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/traffic_target.py delete mode 100644 owl-bot-staging/v2/google/cloud/run_v2/types/vendor_settings.py delete mode 100644 owl-bot-staging/v2/mypy.ini delete mode 100644 owl-bot-staging/v2/noxfile.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_run_v2.json delete mode 100644 owl-bot-staging/v2/scripts/fixup_run_v2_keywords.py delete mode 100644 owl-bot-staging/v2/setup.py delete mode 100644 owl-bot-staging/v2/tests/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/run_v2/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/run_v2/test_revisions.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/run_v2/test_services.py diff --git a/google/cloud/run_v2/services/revisions/async_client.py b/google/cloud/run_v2/services/revisions/async_client.py index 3455cb5..1f4e6cc 100644 --- a/google/cloud/run_v2/services/revisions/async_client.py +++ b/google/cloud/run_v2/services/revisions/async_client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import functools import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core.client_options import ClientOptions @@ -325,7 +325,6 @@ async def list_revisions( r"""List Revisions from a given Service, or from a given location. - .. code-block:: python from google.cloud import run_v2 diff --git a/google/cloud/run_v2/services/revisions/client.py b/google/cloud/run_v2/services/revisions/client.py index 56e7433..378aa58 100644 --- a/google/cloud/run_v2/services/revisions/client.py +++ b/google/cloud/run_v2/services/revisions/client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import os import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib @@ -652,7 +652,6 @@ def list_revisions( r"""List Revisions from a given Service, or from a given location. - .. code-block:: python from google.cloud import run_v2 diff --git a/google/cloud/run_v2/services/revisions/transports/base.py b/google/cloud/run_v2/services/revisions/transports/base.py index 063378e..af36691 100644 --- a/google/cloud/run_v2/services/revisions/transports/base.py +++ b/google/cloud/run_v2/services/revisions/transports/base.py @@ -82,6 +82,7 @@ def __init__( 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" @@ -182,5 +183,9 @@ def delete_revision( ]: raise NotImplementedError() + @property + def kind(self) -> str: + raise NotImplementedError() + __all__ = ("RevisionsTransport",) diff --git a/google/cloud/run_v2/services/revisions/transports/grpc.py b/google/cloud/run_v2/services/revisions/transports/grpc.py index 1f9bbd5..0755113 100644 --- a/google/cloud/run_v2/services/revisions/transports/grpc.py +++ b/google/cloud/run_v2/services/revisions/transports/grpc.py @@ -326,5 +326,9 @@ def delete_revision( def close(self): self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc" + __all__ = ("RevisionsGrpcTransport",) diff --git a/google/cloud/run_v2/services/services/async_client.py b/google/cloud/run_v2/services/services/async_client.py index c229069..5ba28db 100644 --- a/google/cloud/run_v2/services/services/async_client.py +++ b/google/cloud/run_v2/services/services/async_client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import functools import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core.client_options import ClientOptions @@ -230,7 +230,6 @@ async def create_service( r"""Creates a new Service in a given project and location. - .. code-block:: python from google.cloud import run_v2 @@ -443,7 +442,7 @@ def sample_get_service(): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=10.0, ), @@ -554,7 +553,7 @@ def sample_list_services(): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=10.0, ), @@ -722,7 +721,6 @@ async def delete_service( This will cause the Service to stop serving traffic and will delete all revisions. - .. code-block:: python from google.cloud import run_v2 @@ -839,7 +837,6 @@ async def get_iam_policy( for the given Cloud Run Service. This result does not include any inherited policies. - .. code-block:: python from google.cloud import run_v2 @@ -871,21 +868,26 @@ def sample_get_iam_policy(): 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. + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud 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** + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** { "bindings": [ @@ -900,17 +902,17 @@ def sample_get_iam_policy(): }, { "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], + "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')", } } - ] + ], "etag": "BwWWja0YfJA=", "version": 3 } - **YAML Example** + **YAML example:** bindings: - members: - user:\ mike@example.com - group:\ admins@example.com - domain:google.com - @@ -921,11 +923,12 @@ def sample_get_iam_policy(): condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < - timestamp('2020-10-01T00:00:00.000Z') + timestamp('2020-10-01T00:00:00.000Z') etag: + BwWWja0YfJA= version: 3 For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). + [IAM + documentation](\ https://cloud.google.com/iam/docs/). """ # Create or coerce a protobuf request object. @@ -970,7 +973,6 @@ async def set_iam_policy( r"""Sets the IAM Access control policy for the specified Service. Overwrites any existing policy. - .. code-block:: python from google.cloud import run_v2 @@ -1002,21 +1004,26 @@ def sample_set_iam_policy(): 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. + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud 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** + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** { "bindings": [ @@ -1031,17 +1038,17 @@ def sample_set_iam_policy(): }, { "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], + "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')", } } - ] + ], "etag": "BwWWja0YfJA=", "version": 3 } - **YAML Example** + **YAML example:** bindings: - members: - user:\ mike@example.com - group:\ admins@example.com - domain:google.com - @@ -1052,11 +1059,12 @@ def sample_set_iam_policy(): condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < - timestamp('2020-10-01T00:00:00.000Z') + timestamp('2020-10-01T00:00:00.000Z') etag: + BwWWja0YfJA= version: 3 For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). + [IAM + documentation](\ https://cloud.google.com/iam/docs/). """ # Create or coerce a protobuf request object. @@ -1103,7 +1111,6 @@ async def test_iam_permissions( There are no permissions required for making this API call. - .. code-block:: python from google.cloud import run_v2 diff --git a/google/cloud/run_v2/services/services/client.py b/google/cloud/run_v2/services/services/client.py index 2e52170..21522ed 100644 --- a/google/cloud/run_v2/services/services/client.py +++ b/google/cloud/run_v2/services/services/client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import os import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib @@ -559,7 +559,6 @@ def create_service( r"""Creates a new Service in a given project and location. - .. code-block:: python from google.cloud import run_v2 @@ -1033,7 +1032,6 @@ def delete_service( This will cause the Service to stop serving traffic and will delete all revisions. - .. code-block:: python from google.cloud import run_v2 @@ -1150,7 +1148,6 @@ def get_iam_policy( for the given Cloud Run Service. This result does not include any inherited policies. - .. code-block:: python from google.cloud import run_v2 @@ -1182,21 +1179,26 @@ def sample_get_iam_policy(): 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. + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud 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** + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** { "bindings": [ @@ -1211,17 +1213,17 @@ def sample_get_iam_policy(): }, { "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], + "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')", } } - ] + ], "etag": "BwWWja0YfJA=", "version": 3 } - **YAML Example** + **YAML example:** bindings: - members: - user:\ mike@example.com - group:\ admins@example.com - domain:google.com - @@ -1232,11 +1234,12 @@ def sample_get_iam_policy(): condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < - timestamp('2020-10-01T00:00:00.000Z') + timestamp('2020-10-01T00:00:00.000Z') etag: + BwWWja0YfJA= version: 3 For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). + [IAM + documentation](\ https://cloud.google.com/iam/docs/). """ # Create or coerce a protobuf request object. @@ -1280,7 +1283,6 @@ def set_iam_policy( r"""Sets the IAM Access control policy for the specified Service. Overwrites any existing policy. - .. code-block:: python from google.cloud import run_v2 @@ -1312,21 +1314,26 @@ def sample_set_iam_policy(): 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. + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud 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** + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** { "bindings": [ @@ -1341,17 +1348,17 @@ def sample_set_iam_policy(): }, { "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], + "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')", } } - ] + ], "etag": "BwWWja0YfJA=", "version": 3 } - **YAML Example** + **YAML example:** bindings: - members: - user:\ mike@example.com - group:\ admins@example.com - domain:google.com - @@ -1362,11 +1369,12 @@ def sample_set_iam_policy(): condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < - timestamp('2020-10-01T00:00:00.000Z') + timestamp('2020-10-01T00:00:00.000Z') etag: + BwWWja0YfJA= version: 3 For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). + [IAM + documentation](\ https://cloud.google.com/iam/docs/). """ # Create or coerce a protobuf request object. @@ -1412,7 +1420,6 @@ def test_iam_permissions( There are no permissions required for making this API call. - .. code-block:: python from google.cloud import run_v2 diff --git a/google/cloud/run_v2/services/services/transports/base.py b/google/cloud/run_v2/services/services/transports/base.py index fb9473e..79866ea 100644 --- a/google/cloud/run_v2/services/services/transports/base.py +++ b/google/cloud/run_v2/services/services/transports/base.py @@ -85,6 +85,7 @@ def __init__( 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" @@ -137,7 +138,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=10.0, ), @@ -151,7 +152,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=10.0, ), @@ -273,5 +274,9 @@ def test_iam_permissions( ]: raise NotImplementedError() + @property + def kind(self) -> str: + raise NotImplementedError() + __all__ = ("ServicesTransport",) diff --git a/google/cloud/run_v2/services/services/transports/grpc.py b/google/cloud/run_v2/services/services/transports/grpc.py index e77332d..0c0daf0 100644 --- a/google/cloud/run_v2/services/services/transports/grpc.py +++ b/google/cloud/run_v2/services/services/transports/grpc.py @@ -468,5 +468,9 @@ def test_iam_permissions( def close(self): self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc" + __all__ = ("ServicesGrpcTransport",) diff --git a/google/cloud/run_v2/types/__init__.py b/google/cloud/run_v2/types/__init__.py index 4ab6c3f..5a6b804 100644 --- a/google/cloud/run_v2/types/__init__.py +++ b/google/cloud/run_v2/types/__init__.py @@ -13,7 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .condition import Condition +from .condition import ( + Condition, +) from .k8s_min import ( CloudSqlInstance, Container, @@ -34,7 +36,9 @@ ListRevisionsResponse, Revision, ) -from .revision_template import RevisionTemplate +from .revision_template import ( + RevisionTemplate, +) from .service import ( CreateServiceRequest, DeleteServiceRequest, diff --git a/google/cloud/run_v2/types/k8s_min.py b/google/cloud/run_v2/types/k8s_min.py index 2ed4a37..e1be020 100644 --- a/google/cloud/run_v2/types/k8s_min.py +++ b/google/cloud/run_v2/types/k8s_min.py @@ -133,7 +133,7 @@ class ResourceRequirements(proto.Message): requirements. Attributes: - limits (Sequence[google.cloud.run_v2.types.ResourceRequirements.LimitsEntry]): + limits (Mapping[str, str]): Only memory and CPU are supported. Note: The only supported values for CPU are '1', '2', and '4'. Setting 4 CPU requires at least 2Gi of diff --git a/google/cloud/run_v2/types/revision.py b/google/cloud/run_v2/types/revision.py index dd2f6d0..d0670ec 100644 --- a/google/cloud/run_v2/types/revision.py +++ b/google/cloud/run_v2/types/revision.py @@ -169,7 +169,7 @@ class Revision(proto.Message): Output only. A number that monotonically increases every time the user modifies the desired state. - labels (Sequence[google.cloud.run_v2.types.Revision.LabelsEntry]): + labels (Mapping[str, str]): KRM-style labels for the resource. User-provided labels are shared with Google's billing system, so they can be used to filter, @@ -183,7 +183,7 @@ class Revision(proto.Message): 'run.googleapis.com' or 'serving.knative.dev' namespaces. Those labels are read-only, and user changes will not be preserved. - annotations (Sequence[google.cloud.run_v2.types.Revision.AnnotationsEntry]): + annotations (Mapping[str, str]): KRM-style annotations for the resource. create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The creation time. diff --git a/google/cloud/run_v2/types/revision_template.py b/google/cloud/run_v2/types/revision_template.py index 22066b2..a526b82 100644 --- a/google/cloud/run_v2/types/revision_template.py +++ b/google/cloud/run_v2/types/revision_template.py @@ -37,9 +37,9 @@ class RevisionTemplate(proto.Message): The unique name for the revision. If this field is omitted, it will be automatically generated based on the Service name. - labels (Sequence[google.cloud.run_v2.types.RevisionTemplate.LabelsEntry]): + labels (Mapping[str, str]): KRM-style labels for the resource. - annotations (Sequence[google.cloud.run_v2.types.RevisionTemplate.AnnotationsEntry]): + annotations (Mapping[str, str]): KRM-style annotations for the resource. scaling (google.cloud.run_v2.types.RevisionScaling): Scaling settings for this Revision. diff --git a/google/cloud/run_v2/types/service.py b/google/cloud/run_v2/types/service.py index bd8e1dd..3a77ee4 100644 --- a/google/cloud/run_v2/types/service.py +++ b/google/cloud/run_v2/types/service.py @@ -258,7 +258,7 @@ class Service(proto.Message): Output only. A number that monotonically increases every time the user modifies the desired state. - labels (Sequence[google.cloud.run_v2.types.Service.LabelsEntry]): + labels (Mapping[str, str]): Map of string keys and values that can be used to organize and categorize objects. User-provided labels are shared with Google's @@ -273,7 +273,7 @@ class Service(proto.Message): 'run.googleapis.com' or 'serving.knative.dev' namespaces. Those labels are read-only, and user changes will not be preserved. - annotations (Sequence[google.cloud.run_v2.types.Service.AnnotationsEntry]): + annotations (Mapping[str, str]): Unstructured key value map that may be set by external tools to store and arbitrary metadata. They are not queryable and should be preserved diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc deleted file mode 100644 index 03a3142..0000000 --- a/owl-bot-staging/v2/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/run/__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/v2/.flake8 b/owl-bot-staging/v2/.flake8 deleted file mode 100644 index 29227d4..0000000 --- a/owl-bot-staging/v2/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in deleted file mode 100644 index fb6bb81..0000000 --- a/owl-bot-staging/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/run *.py -recursive-include google/cloud/run_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst deleted file mode 100644 index ca52f66..0000000 --- a/owl-bot-staging/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Run 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 Run 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/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py deleted file mode 100644 index f4aa161..0000000 --- a/owl-bot-staging/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-run documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-run" -copyright = u"2022, 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-run-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-run.tex", - u"google-cloud-run Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-run", - u"Google Cloud Run Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-run", - u"google-cloud-run Documentation", - author, - "google-cloud-run", - "GAPIC library for Google Cloud Run 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/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst deleted file mode 100644 index da0a990..0000000 --- a/owl-bot-staging/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - run_v2/services - run_v2/types diff --git a/owl-bot-staging/v2/docs/run_v2/revisions.rst b/owl-bot-staging/v2/docs/run_v2/revisions.rst deleted file mode 100644 index e4b2219..0000000 --- a/owl-bot-staging/v2/docs/run_v2/revisions.rst +++ /dev/null @@ -1,10 +0,0 @@ -Revisions ---------------------------- - -.. automodule:: google.cloud.run_v2.services.revisions - :members: - :inherited-members: - -.. automodule:: google.cloud.run_v2.services.revisions.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/run_v2/services.rst b/owl-bot-staging/v2/docs/run_v2/services.rst deleted file mode 100644 index 533d18a..0000000 --- a/owl-bot-staging/v2/docs/run_v2/services.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Run v2 API -==================================== -.. toctree:: - :maxdepth: 2 - - revisions - services diff --git a/owl-bot-staging/v2/docs/run_v2/types.rst b/owl-bot-staging/v2/docs/run_v2/types.rst deleted file mode 100644 index a45661d..0000000 --- a/owl-bot-staging/v2/docs/run_v2/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Run v2 API -================================= - -.. automodule:: google.cloud.run_v2.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2/google/cloud/run/__init__.py b/owl-bot-staging/v2/google/cloud/run/__init__.py deleted file mode 100644 index 48668d4..0000000 --- a/owl-bot-staging/v2/google/cloud/run/__init__.py +++ /dev/null @@ -1,93 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.run_v2.services.revisions.client import RevisionsClient -from google.cloud.run_v2.services.revisions.async_client import RevisionsAsyncClient -from google.cloud.run_v2.services.services.client import ServicesClient -from google.cloud.run_v2.services.services.async_client import ServicesAsyncClient - -from google.cloud.run_v2.types.condition import Condition -from google.cloud.run_v2.types.k8s_min import CloudSqlInstance -from google.cloud.run_v2.types.k8s_min import Container -from google.cloud.run_v2.types.k8s_min import ContainerPort -from google.cloud.run_v2.types.k8s_min import EnvVar -from google.cloud.run_v2.types.k8s_min import EnvVarSource -from google.cloud.run_v2.types.k8s_min import ResourceRequirements -from google.cloud.run_v2.types.k8s_min import SecretKeySelector -from google.cloud.run_v2.types.k8s_min import SecretVolumeSource -from google.cloud.run_v2.types.k8s_min import VersionToPath -from google.cloud.run_v2.types.k8s_min import Volume -from google.cloud.run_v2.types.k8s_min import VolumeMount -from google.cloud.run_v2.types.revision import DeleteRevisionRequest -from google.cloud.run_v2.types.revision import GetRevisionRequest -from google.cloud.run_v2.types.revision import ListRevisionsRequest -from google.cloud.run_v2.types.revision import ListRevisionsResponse -from google.cloud.run_v2.types.revision import Revision -from google.cloud.run_v2.types.revision_template import RevisionTemplate -from google.cloud.run_v2.types.service import CreateServiceRequest -from google.cloud.run_v2.types.service import DeleteServiceRequest -from google.cloud.run_v2.types.service import GetServiceRequest -from google.cloud.run_v2.types.service import ListServicesRequest -from google.cloud.run_v2.types.service import ListServicesResponse -from google.cloud.run_v2.types.service import Service -from google.cloud.run_v2.types.service import UpdateServiceRequest -from google.cloud.run_v2.types.traffic_target import TrafficTarget -from google.cloud.run_v2.types.traffic_target import TrafficTargetStatus -from google.cloud.run_v2.types.traffic_target import TrafficTargetAllocationType -from google.cloud.run_v2.types.vendor_settings import BinaryAuthorization -from google.cloud.run_v2.types.vendor_settings import RevisionScaling -from google.cloud.run_v2.types.vendor_settings import VpcAccess -from google.cloud.run_v2.types.vendor_settings import ExecutionEnvironment -from google.cloud.run_v2.types.vendor_settings import IngressTraffic - -__all__ = ('RevisionsClient', - 'RevisionsAsyncClient', - 'ServicesClient', - 'ServicesAsyncClient', - 'Condition', - 'CloudSqlInstance', - 'Container', - 'ContainerPort', - 'EnvVar', - 'EnvVarSource', - 'ResourceRequirements', - 'SecretKeySelector', - 'SecretVolumeSource', - 'VersionToPath', - 'Volume', - 'VolumeMount', - 'DeleteRevisionRequest', - 'GetRevisionRequest', - 'ListRevisionsRequest', - 'ListRevisionsResponse', - 'Revision', - 'RevisionTemplate', - 'CreateServiceRequest', - 'DeleteServiceRequest', - 'GetServiceRequest', - 'ListServicesRequest', - 'ListServicesResponse', - 'Service', - 'UpdateServiceRequest', - 'TrafficTarget', - 'TrafficTargetStatus', - 'TrafficTargetAllocationType', - 'BinaryAuthorization', - 'RevisionScaling', - 'VpcAccess', - 'ExecutionEnvironment', - 'IngressTraffic', -) diff --git a/owl-bot-staging/v2/google/cloud/run/py.typed b/owl-bot-staging/v2/google/cloud/run/py.typed deleted file mode 100644 index a94ba23..0000000 --- a/owl-bot-staging/v2/google/cloud/run/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-run package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/run_v2/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/__init__.py deleted file mode 100644 index 8ba23e1..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/__init__.py +++ /dev/null @@ -1,94 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.revisions import RevisionsClient -from .services.revisions import RevisionsAsyncClient -from .services.services import ServicesClient -from .services.services import ServicesAsyncClient - -from .types.condition import Condition -from .types.k8s_min import CloudSqlInstance -from .types.k8s_min import Container -from .types.k8s_min import ContainerPort -from .types.k8s_min import EnvVar -from .types.k8s_min import EnvVarSource -from .types.k8s_min import ResourceRequirements -from .types.k8s_min import SecretKeySelector -from .types.k8s_min import SecretVolumeSource -from .types.k8s_min import VersionToPath -from .types.k8s_min import Volume -from .types.k8s_min import VolumeMount -from .types.revision import DeleteRevisionRequest -from .types.revision import GetRevisionRequest -from .types.revision import ListRevisionsRequest -from .types.revision import ListRevisionsResponse -from .types.revision import Revision -from .types.revision_template import RevisionTemplate -from .types.service import CreateServiceRequest -from .types.service import DeleteServiceRequest -from .types.service import GetServiceRequest -from .types.service import ListServicesRequest -from .types.service import ListServicesResponse -from .types.service import Service -from .types.service import UpdateServiceRequest -from .types.traffic_target import TrafficTarget -from .types.traffic_target import TrafficTargetStatus -from .types.traffic_target import TrafficTargetAllocationType -from .types.vendor_settings import BinaryAuthorization -from .types.vendor_settings import RevisionScaling -from .types.vendor_settings import VpcAccess -from .types.vendor_settings import ExecutionEnvironment -from .types.vendor_settings import IngressTraffic - -__all__ = ( - 'RevisionsAsyncClient', - 'ServicesAsyncClient', -'BinaryAuthorization', -'CloudSqlInstance', -'Condition', -'Container', -'ContainerPort', -'CreateServiceRequest', -'DeleteRevisionRequest', -'DeleteServiceRequest', -'EnvVar', -'EnvVarSource', -'ExecutionEnvironment', -'GetRevisionRequest', -'GetServiceRequest', -'IngressTraffic', -'ListRevisionsRequest', -'ListRevisionsResponse', -'ListServicesRequest', -'ListServicesResponse', -'ResourceRequirements', -'Revision', -'RevisionScaling', -'RevisionTemplate', -'RevisionsClient', -'SecretKeySelector', -'SecretVolumeSource', -'Service', -'ServicesClient', -'TrafficTarget', -'TrafficTargetAllocationType', -'TrafficTargetStatus', -'UpdateServiceRequest', -'VersionToPath', -'Volume', -'VolumeMount', -'VpcAccess', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/run_v2/gapic_metadata.json deleted file mode 100644 index 995df8c..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/gapic_metadata.json +++ /dev/null @@ -1,147 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.run_v2", - "protoPackage": "google.cloud.run.v2", - "schema": "1.0", - "services": { - "Revisions": { - "clients": { - "grpc": { - "libraryClient": "RevisionsClient", - "rpcs": { - "DeleteRevision": { - "methods": [ - "delete_revision" - ] - }, - "GetRevision": { - "methods": [ - "get_revision" - ] - }, - "ListRevisions": { - "methods": [ - "list_revisions" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RevisionsAsyncClient", - "rpcs": { - "DeleteRevision": { - "methods": [ - "delete_revision" - ] - }, - "GetRevision": { - "methods": [ - "get_revision" - ] - }, - "ListRevisions": { - "methods": [ - "list_revisions" - ] - } - } - } - } - }, - "Services": { - "clients": { - "grpc": { - "libraryClient": "ServicesClient", - "rpcs": { - "CreateService": { - "methods": [ - "create_service" - ] - }, - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateService": { - "methods": [ - "update_service" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServicesAsyncClient", - "rpcs": { - "CreateService": { - "methods": [ - "create_service" - ] - }, - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateService": { - "methods": [ - "update_service" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2/google/cloud/run_v2/py.typed b/owl-bot-staging/v2/google/cloud/run_v2/py.typed deleted file mode 100644 index a94ba23..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-run package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/services/__init__.py deleted file mode 100644 index e8e1c38..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v2/google/cloud/run_v2/services/revisions/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/__init__.py deleted file mode 100644 index 1ffa1d4..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 RevisionsClient -from .async_client import RevisionsAsyncClient - -__all__ = ( - 'RevisionsClient', - 'RevisionsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/async_client.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/async_client.py deleted file mode 100644 index 4264b3d..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/async_client.py +++ /dev/null @@ -1,543 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.run_v2.services.revisions import pagers -from google.cloud.run_v2.types import condition -from google.cloud.run_v2.types import k8s_min -from google.cloud.run_v2.types import revision -from google.cloud.run_v2.types import vendor_settings -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import RevisionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RevisionsGrpcAsyncIOTransport -from .client import RevisionsClient - - -class RevisionsAsyncClient: - """Cloud Run Revision Control Plane API.""" - - _client: RevisionsClient - - DEFAULT_ENDPOINT = RevisionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RevisionsClient.DEFAULT_MTLS_ENDPOINT - - connector_path = staticmethod(RevisionsClient.connector_path) - parse_connector_path = staticmethod(RevisionsClient.parse_connector_path) - crypto_key_path = staticmethod(RevisionsClient.crypto_key_path) - parse_crypto_key_path = staticmethod(RevisionsClient.parse_crypto_key_path) - revision_path = staticmethod(RevisionsClient.revision_path) - parse_revision_path = staticmethod(RevisionsClient.parse_revision_path) - secret_path = staticmethod(RevisionsClient.secret_path) - parse_secret_path = staticmethod(RevisionsClient.parse_secret_path) - secret_version_path = staticmethod(RevisionsClient.secret_version_path) - parse_secret_version_path = staticmethod(RevisionsClient.parse_secret_version_path) - service_path = staticmethod(RevisionsClient.service_path) - parse_service_path = staticmethod(RevisionsClient.parse_service_path) - common_billing_account_path = staticmethod(RevisionsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RevisionsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RevisionsClient.common_folder_path) - parse_common_folder_path = staticmethod(RevisionsClient.parse_common_folder_path) - common_organization_path = staticmethod(RevisionsClient.common_organization_path) - parse_common_organization_path = staticmethod(RevisionsClient.parse_common_organization_path) - common_project_path = staticmethod(RevisionsClient.common_project_path) - parse_common_project_path = staticmethod(RevisionsClient.parse_common_project_path) - common_location_path = staticmethod(RevisionsClient.common_location_path) - parse_common_location_path = staticmethod(RevisionsClient.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: - RevisionsAsyncClient: The constructed client. - """ - return RevisionsClient.from_service_account_info.__func__(RevisionsAsyncClient, 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: - RevisionsAsyncClient: The constructed client. - """ - return RevisionsClient.from_service_account_file.__func__(RevisionsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RevisionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RevisionsTransport: - """Returns the transport used by the client instance. - - Returns: - RevisionsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RevisionsClient).get_transport_class, type(RevisionsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, RevisionsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the revisions 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, ~.RevisionsTransport]): 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 = RevisionsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_revision(self, - request: Union[revision.GetRevisionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> revision.Revision: - r"""Gets information about a Revision. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_get_revision(): - # Create a client - client = run_v2.RevisionsClient() - - # Initialize request argument(s) - request = run_v2.GetRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.get_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.GetRevisionRequest, dict]): - The request object. Request message for obtaining a - Revision by its full name. - name (:class:`str`): - Required. The full name of the - Revision. Format: - projects/{project}/locations/{location}/services/{service}/revisions/{revision} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.run_v2.types.Revision: - A Revision is an immutable snapshot - of code and configuration. A Revision - references a container image. Revisions - are only created by updates to its - parent Service. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = revision.GetRevisionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_revision, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_revisions(self, - request: Union[revision.ListRevisionsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListRevisionsAsyncPager: - r"""List Revisions from a given Service, or from a given - location. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_list_revisions(): - # Create a client - client = run_v2.RevisionsClient() - - # Initialize request argument(s) - request = run_v2.ListRevisionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.run_v2.types.ListRevisionsRequest, dict]): - The request object. Request message for retrieving a - list of Revisions. - parent (:class:`str`): - Required. The Service from which the - Revisions should be listed. To list all - Revisions across Services, use "-" - instead of Service name. Format: - projects/{project}/locations/{location}/services/{service} - - 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.run_v2.services.revisions.pagers.ListRevisionsAsyncPager: - Response message containing a list of - Revisions. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = revision.ListRevisionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_revisions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListRevisionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_revision(self, - request: Union[revision.DeleteRevisionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Delete a Revision. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_delete_revision(): - # Create a client - client = run_v2.RevisionsClient() - - # Initialize request argument(s) - request = run_v2.DeleteRevisionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_revision(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.DeleteRevisionRequest, dict]): - The request object. Request message for deleting a - retired Revision. Revision lifecycle is usually managed - by making changes to the parent Service. Only retired - revisions can be deleted with this API. - name (:class:`str`): - Required. The name of the Revision to - delete. Format: - projects/{project}/locations/{location}/services/{service}/revisions/{revision} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.run_v2.types.Revision` A Revision is an immutable snapshot of code and configuration. A Revision - references a container image. Revisions are only - created by updates to its parent Service. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = revision.DeleteRevisionRequest(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_revision, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - revision.Revision, - metadata_type=revision.Revision, - ) - - # 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-run", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "RevisionsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/client.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/client.py deleted file mode 100644 index 8aeda60..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/client.py +++ /dev/null @@ -1,787 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.run_v2.services.revisions import pagers -from google.cloud.run_v2.types import condition -from google.cloud.run_v2.types import k8s_min -from google.cloud.run_v2.types import revision -from google.cloud.run_v2.types import vendor_settings -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import RevisionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RevisionsGrpcTransport -from .transports.grpc_asyncio import RevisionsGrpcAsyncIOTransport - - -class RevisionsClientMeta(type): - """Metaclass for the Revisions 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[RevisionsTransport]] - _transport_registry["grpc"] = RevisionsGrpcTransport - _transport_registry["grpc_asyncio"] = RevisionsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[RevisionsTransport]: - """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 RevisionsClient(metaclass=RevisionsClientMeta): - """Cloud Run Revision Control Plane API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "run.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: - RevisionsClient: 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: - RevisionsClient: 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) -> RevisionsTransport: - """Returns the transport used by the client instance. - - Returns: - RevisionsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def connector_path(project: str,location: str,connector: str,) -> str: - """Returns a fully-qualified connector string.""" - return "projects/{project}/locations/{location}/connectors/{connector}".format(project=project, location=location, connector=connector, ) - - @staticmethod - def parse_connector_path(path: str) -> Dict[str,str]: - """Parses a connector path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/connectors/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: - """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - - @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: - """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def revision_path(project: str,location: str,service: str,revision: str,) -> str: - """Returns a fully-qualified revision string.""" - return "projects/{project}/locations/{location}/services/{service}/revisions/{revision}".format(project=project, location=location, service=service, revision=revision, ) - - @staticmethod - def parse_revision_path(path: str) -> Dict[str,str]: - """Parses a revision path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)/revisions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def secret_path(project: str,secret: str,) -> str: - """Returns a fully-qualified secret string.""" - return "projects/{project}/secrets/{secret}".format(project=project, secret=secret, ) - - @staticmethod - def parse_secret_path(path: str) -> Dict[str,str]: - """Parses a secret path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def secret_version_path(project: str,secret: str,version: str,) -> str: - """Returns a fully-qualified secret_version string.""" - return "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) - - @staticmethod - def parse_secret_version_path(path: str) -> Dict[str,str]: - """Parses a secret_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_path(project: str,location: str,service: str,) -> str: - """Returns a fully-qualified service string.""" - return "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, 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.+?)/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 {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RevisionsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the revisions 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, RevisionsTransport]): 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() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RevisionsTransport): - # transport is a RevisionsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def get_revision(self, - request: Union[revision.GetRevisionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> revision.Revision: - r"""Gets information about a Revision. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_get_revision(): - # Create a client - client = run_v2.RevisionsClient() - - # Initialize request argument(s) - request = run_v2.GetRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.get_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.GetRevisionRequest, dict]): - The request object. Request message for obtaining a - Revision by its full name. - name (str): - Required. The full name of the - Revision. Format: - projects/{project}/locations/{location}/services/{service}/revisions/{revision} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.run_v2.types.Revision: - A Revision is an immutable snapshot - of code and configuration. A Revision - references a container image. Revisions - are only created by updates to its - parent Service. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a revision.GetRevisionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, revision.GetRevisionRequest): - request = revision.GetRevisionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_revision] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_revisions(self, - request: Union[revision.ListRevisionsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListRevisionsPager: - r"""List Revisions from a given Service, or from a given - location. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_list_revisions(): - # Create a client - client = run_v2.RevisionsClient() - - # Initialize request argument(s) - request = run_v2.ListRevisionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.run_v2.types.ListRevisionsRequest, dict]): - The request object. Request message for retrieving a - list of Revisions. - parent (str): - Required. The Service from which the - Revisions should be listed. To list all - Revisions across Services, use "-" - instead of Service name. Format: - projects/{project}/locations/{location}/services/{service} - - 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.run_v2.services.revisions.pagers.ListRevisionsPager: - Response message containing a list of - Revisions. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a revision.ListRevisionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, revision.ListRevisionsRequest): - request = revision.ListRevisionsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_revisions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListRevisionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_revision(self, - request: Union[revision.DeleteRevisionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Delete a Revision. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_delete_revision(): - # Create a client - client = run_v2.RevisionsClient() - - # Initialize request argument(s) - request = run_v2.DeleteRevisionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_revision(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.DeleteRevisionRequest, dict]): - The request object. Request message for deleting a - retired Revision. Revision lifecycle is usually managed - by making changes to the parent Service. Only retired - revisions can be deleted with this API. - name (str): - Required. The name of the Revision to - delete. Format: - projects/{project}/locations/{location}/services/{service}/revisions/{revision} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.run_v2.types.Revision` A Revision is an immutable snapshot of code and configuration. A Revision - references a container image. Revisions are only - created by updates to its parent Service. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a revision.DeleteRevisionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, revision.DeleteRevisionRequest): - request = revision.DeleteRevisionRequest(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_revision] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - revision.Revision, - metadata_type=revision.Revision, - ) - - # 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-run", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "RevisionsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/pagers.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/pagers.py deleted file mode 100644 index 9027d58..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.run_v2.types import revision - - -class ListRevisionsPager: - """A pager for iterating through ``list_revisions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.run_v2.types.ListRevisionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``revisions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListRevisions`` requests and continue to iterate - through the ``revisions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.run_v2.types.ListRevisionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., revision.ListRevisionsResponse], - request: revision.ListRevisionsRequest, - response: revision.ListRevisionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.run_v2.types.ListRevisionsRequest): - The initial request object. - response (google.cloud.run_v2.types.ListRevisionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = revision.ListRevisionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[revision.ListRevisionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[revision.Revision]: - for page in self.pages: - yield from page.revisions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListRevisionsAsyncPager: - """A pager for iterating through ``list_revisions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.run_v2.types.ListRevisionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``revisions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListRevisions`` requests and continue to iterate - through the ``revisions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.run_v2.types.ListRevisionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[revision.ListRevisionsResponse]], - request: revision.ListRevisionsRequest, - response: revision.ListRevisionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.run_v2.types.ListRevisionsRequest): - The initial request object. - response (google.cloud.run_v2.types.ListRevisionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = revision.ListRevisionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[revision.ListRevisionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[revision.Revision]: - async def async_generator(): - async for page in self.pages: - for response in page.revisions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/__init__.py deleted file mode 100644 index 2153a3a..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 RevisionsTransport -from .grpc import RevisionsGrpcTransport -from .grpc_asyncio import RevisionsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RevisionsTransport]] -_transport_registry['grpc'] = RevisionsGrpcTransport -_transport_registry['grpc_asyncio'] = RevisionsGrpcAsyncIOTransport - -__all__ = ( - 'RevisionsTransport', - 'RevisionsGrpcTransport', - 'RevisionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/base.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/base.py deleted file mode 100644 index 9dfa562..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/base.py +++ /dev/null @@ -1,185 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.run_v2.types import revision -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-run', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class RevisionsTransport(abc.ABC): - """Abstract transport class for Revisions.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'run.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_revision: gapic_v1.method.wrap_method( - self.get_revision, - default_timeout=None, - client_info=client_info, - ), - self.list_revisions: gapic_v1.method.wrap_method( - self.list_revisions, - default_timeout=None, - client_info=client_info, - ), - self.delete_revision: gapic_v1.method.wrap_method( - self.delete_revision, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_revision(self) -> Callable[ - [revision.GetRevisionRequest], - Union[ - revision.Revision, - Awaitable[revision.Revision] - ]]: - raise NotImplementedError() - - @property - def list_revisions(self) -> Callable[ - [revision.ListRevisionsRequest], - Union[ - revision.ListRevisionsResponse, - Awaitable[revision.ListRevisionsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_revision(self) -> Callable[ - [revision.DeleteRevisionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RevisionsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc.py deleted file mode 100644 index 6aeada1..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc.py +++ /dev/null @@ -1,334 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.run_v2.types import revision -from google.longrunning import operations_pb2 # type: ignore -from .base import RevisionsTransport, DEFAULT_CLIENT_INFO - - -class RevisionsGrpcTransport(RevisionsTransport): - """gRPC backend transport for Revisions. - - Cloud Run Revision Control Plane API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'run.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] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'run.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 operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_revision(self) -> Callable[ - [revision.GetRevisionRequest], - revision.Revision]: - r"""Return a callable for the get revision method over gRPC. - - Gets information about a Revision. - - Returns: - Callable[[~.GetRevisionRequest], - ~.Revision]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_revision' not in self._stubs: - self._stubs['get_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Revisions/GetRevision', - request_serializer=revision.GetRevisionRequest.serialize, - response_deserializer=revision.Revision.deserialize, - ) - return self._stubs['get_revision'] - - @property - def list_revisions(self) -> Callable[ - [revision.ListRevisionsRequest], - revision.ListRevisionsResponse]: - r"""Return a callable for the list revisions method over gRPC. - - List Revisions from a given Service, or from a given - location. - - Returns: - Callable[[~.ListRevisionsRequest], - ~.ListRevisionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_revisions' not in self._stubs: - self._stubs['list_revisions'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Revisions/ListRevisions', - request_serializer=revision.ListRevisionsRequest.serialize, - response_deserializer=revision.ListRevisionsResponse.deserialize, - ) - return self._stubs['list_revisions'] - - @property - def delete_revision(self) -> Callable[ - [revision.DeleteRevisionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete revision method over gRPC. - - Delete a Revision. - - Returns: - Callable[[~.DeleteRevisionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_revision' not in self._stubs: - self._stubs['delete_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Revisions/DeleteRevision', - request_serializer=revision.DeleteRevisionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_revision'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RevisionsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py deleted file mode 100644 index 15dd3ef..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py +++ /dev/null @@ -1,333 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.run_v2.types import revision -from google.longrunning import operations_pb2 # type: ignore -from .base import RevisionsTransport, DEFAULT_CLIENT_INFO -from .grpc import RevisionsGrpcTransport - - -class RevisionsGrpcAsyncIOTransport(RevisionsTransport): - """gRPC AsyncIO backend transport for Revisions. - - Cloud Run Revision Control Plane API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'run.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 = 'run.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] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_revision(self) -> Callable[ - [revision.GetRevisionRequest], - Awaitable[revision.Revision]]: - r"""Return a callable for the get revision method over gRPC. - - Gets information about a Revision. - - Returns: - Callable[[~.GetRevisionRequest], - Awaitable[~.Revision]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_revision' not in self._stubs: - self._stubs['get_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Revisions/GetRevision', - request_serializer=revision.GetRevisionRequest.serialize, - response_deserializer=revision.Revision.deserialize, - ) - return self._stubs['get_revision'] - - @property - def list_revisions(self) -> Callable[ - [revision.ListRevisionsRequest], - Awaitable[revision.ListRevisionsResponse]]: - r"""Return a callable for the list revisions method over gRPC. - - List Revisions from a given Service, or from a given - location. - - Returns: - Callable[[~.ListRevisionsRequest], - Awaitable[~.ListRevisionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_revisions' not in self._stubs: - self._stubs['list_revisions'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Revisions/ListRevisions', - request_serializer=revision.ListRevisionsRequest.serialize, - response_deserializer=revision.ListRevisionsResponse.deserialize, - ) - return self._stubs['list_revisions'] - - @property - def delete_revision(self) -> Callable[ - [revision.DeleteRevisionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete revision method over gRPC. - - Delete a Revision. - - Returns: - Callable[[~.DeleteRevisionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_revision' not in self._stubs: - self._stubs['delete_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Revisions/DeleteRevision', - request_serializer=revision.DeleteRevisionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_revision'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'RevisionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/__init__.py deleted file mode 100644 index 531e71a..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/services/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ServicesClient -from .async_client import ServicesAsyncClient - -__all__ = ( - 'ServicesClient', - 'ServicesAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/async_client.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/async_client.py deleted file mode 100644 index bfbdd35..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/services/async_client.py +++ /dev/null @@ -1,1176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.run_v2.services.services import pagers -from google.cloud.run_v2.types import condition -from google.cloud.run_v2.types import revision_template -from google.cloud.run_v2.types import service -from google.cloud.run_v2.types import service as gcr_service -from google.cloud.run_v2.types import traffic_target -from google.cloud.run_v2.types import vendor_settings -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 ServicesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport -from .client import ServicesClient - - -class ServicesAsyncClient: - """Cloud Run Service Control Plane API""" - - _client: ServicesClient - - DEFAULT_ENDPOINT = ServicesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServicesClient.DEFAULT_MTLS_ENDPOINT - - connector_path = staticmethod(ServicesClient.connector_path) - parse_connector_path = staticmethod(ServicesClient.parse_connector_path) - crypto_key_path = staticmethod(ServicesClient.crypto_key_path) - parse_crypto_key_path = staticmethod(ServicesClient.parse_crypto_key_path) - revision_path = staticmethod(ServicesClient.revision_path) - parse_revision_path = staticmethod(ServicesClient.parse_revision_path) - secret_path = staticmethod(ServicesClient.secret_path) - parse_secret_path = staticmethod(ServicesClient.parse_secret_path) - secret_version_path = staticmethod(ServicesClient.secret_version_path) - parse_secret_version_path = staticmethod(ServicesClient.parse_secret_version_path) - service_path = staticmethod(ServicesClient.service_path) - parse_service_path = staticmethod(ServicesClient.parse_service_path) - common_billing_account_path = staticmethod(ServicesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServicesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServicesClient.common_folder_path) - parse_common_folder_path = staticmethod(ServicesClient.parse_common_folder_path) - common_organization_path = staticmethod(ServicesClient.common_organization_path) - parse_common_organization_path = staticmethod(ServicesClient.parse_common_organization_path) - common_project_path = staticmethod(ServicesClient.common_project_path) - parse_common_project_path = staticmethod(ServicesClient.parse_common_project_path) - common_location_path = staticmethod(ServicesClient.common_location_path) - parse_common_location_path = staticmethod(ServicesClient.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: - ServicesAsyncClient: The constructed client. - """ - return ServicesClient.from_service_account_info.__func__(ServicesAsyncClient, 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: - ServicesAsyncClient: The constructed client. - """ - return ServicesClient.from_service_account_file.__func__(ServicesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ServicesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ServicesTransport: - """Returns the transport used by the client instance. - - Returns: - ServicesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ServicesClient).get_transport_class, type(ServicesClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ServicesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the services 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, ~.ServicesTransport]): 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 = ServicesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_service(self, - request: Union[gcr_service.CreateServiceRequest, dict] = None, - *, - parent: str = None, - service: gcr_service.Service = None, - service_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new Service in a given project and - location. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_create_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.CreateServiceRequest( - parent="parent_value", - service_id="service_id_value", - ) - - # Make the request - operation = client.create_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.CreateServiceRequest, dict]): - The request object. Request message for creating a - Service. - parent (:class:`str`): - Required. The location and project in - which this service should be created. - Format: - projects/{projectnumber}/locations/{location} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service (:class:`google.cloud.run_v2.types.Service`): - Required. The Service instance to - create. - - 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 unique identifier for the Service. The - name of the service becomes - {parent}/services/{service_id}. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of - configurations and revision templates which implement - a network service. Service exists to provide a - singular abstraction which can be access controlled, - reasoned about, and which encapsulates software - lifecycle decisions such as rollout policy and team - resource ownership. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 = gcr_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=15.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcr_service.Service, - metadata_type=gcr_service.Service, - ) - - # Done; return the response. - return response - - async def get_service(self, - request: Union[service.GetServiceRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.Service: - r"""Gets information about a Service. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_get_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.GetServiceRequest( - name="name_value", - ) - - # Make the request - response = client.get_service(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.GetServiceRequest, dict]): - The request object. Request message for obtaining a - Service by its full name. - name (:class:`str`): - Required. The full name of the - Service. Format: - projects/{projectnumber}/locations/{location}/services/{service} - - 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.run_v2.types.Service: - Service acts as a top-level container - that manages a set of configurations and - revision templates which implement a - network service. Service exists to - provide a singular abstraction which can - be access controlled, reasoned about, - and which encapsulates software - lifecycle decisions such as rollout - policy and team resource ownership. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_services(self, - request: Union[service.ListServicesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServicesAsyncPager: - r"""List Services. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_list_services(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.ListServicesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_services(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.run_v2.types.ListServicesRequest, dict]): - The request object. Request message for retrieving a - list of Services. - parent (:class:`str`): - Required. The location and project to - list resources on. Location must be a - valid GCP region, and may not be the "-" - wildcard. Format: - projects/{projectnumber}/locations/{location} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.run_v2.services.services.pagers.ListServicesAsyncPager: - Response message containing a list of - Services. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, - ), - deadline=10.0, - ), - default_timeout=10.0, - 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 update_service(self, - request: Union[gcr_service.UpdateServiceRequest, dict] = None, - *, - service: gcr_service.Service = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates a Service. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_update_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.UpdateServiceRequest( - ) - - # Make the request - operation = client.update_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.UpdateServiceRequest, dict]): - The request object. Request message for updating a - service. - service (:class:`google.cloud.run_v2.types.Service`): - Required. The Service to be updated. - 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`): - The list of fields to be updated. - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of - configurations and revision templates which implement - a network service. Service exists to provide a - singular abstraction which can be access controlled, - reasoned about, and which encapsulates software - lifecycle decisions such as rollout policy and team - resource ownership. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service, 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 = gcr_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=15.0, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcr_service.Service, - metadata_type=gcr_service.Service, - ) - - # Done; return the response. - return response - - async def delete_service(self, - request: Union[service.DeleteServiceRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a Service. - This will cause the Service to stop serving traffic and - will delete all revisions. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_delete_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.DeleteServiceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.DeleteServiceRequest, dict]): - The request object. Request message to delete a Service - by its full name. - name (:class:`str`): - Required. The full name of the - Service. Format: - projects/{projectnumber}/locations/{location}/services/{service} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of - configurations and revision templates which implement - a network service. Service exists to provide a - singular abstraction which can be access controlled, - reasoned about, and which encapsulates software - lifecycle decisions such as rollout policy and team - resource ownership. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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=10.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - service.Service, - metadata_type=service.Service, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Get the IAM Access Control policy currently in effect - for the given Cloud Run Service. This result does not - include any inherited policies. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_get_iam_policy(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - 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: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ 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: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM Access control policy for the specified - Service. Overwrites any existing policy. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_set_iam_policy(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - 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: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ 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: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns permissions that a caller has on the - specified Project. - There are no permissions required for making this API - call. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_test_iam_permissions(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value_1', 'permissions_value_2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - 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. - # 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-run", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServicesAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/client.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/client.py deleted file mode 100644 index 9caff13..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/services/client.py +++ /dev/null @@ -1,1405 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.run_v2.services.services import pagers -from google.cloud.run_v2.types import condition -from google.cloud.run_v2.types import revision_template -from google.cloud.run_v2.types import service -from google.cloud.run_v2.types import service as gcr_service -from google.cloud.run_v2.types import traffic_target -from google.cloud.run_v2.types import vendor_settings -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 ServicesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServicesGrpcTransport -from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport - - -class ServicesClientMeta(type): - """Metaclass for the Services 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[ServicesTransport]] - _transport_registry["grpc"] = ServicesGrpcTransport - _transport_registry["grpc_asyncio"] = ServicesGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ServicesTransport]: - """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 ServicesClient(metaclass=ServicesClientMeta): - """Cloud Run Service Control Plane API""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "run.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: - ServicesClient: 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: - ServicesClient: 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) -> ServicesTransport: - """Returns the transport used by the client instance. - - Returns: - ServicesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def connector_path(project: str,location: str,connector: str,) -> str: - """Returns a fully-qualified connector string.""" - return "projects/{project}/locations/{location}/connectors/{connector}".format(project=project, location=location, connector=connector, ) - - @staticmethod - def parse_connector_path(path: str) -> Dict[str,str]: - """Parses a connector path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/connectors/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: - """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - - @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: - """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def revision_path(project: str,location: str,service: str,revision: str,) -> str: - """Returns a fully-qualified revision string.""" - return "projects/{project}/locations/{location}/services/{service}/revisions/{revision}".format(project=project, location=location, service=service, revision=revision, ) - - @staticmethod - def parse_revision_path(path: str) -> Dict[str,str]: - """Parses a revision path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)/revisions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def secret_path(project: str,secret: str,) -> str: - """Returns a fully-qualified secret string.""" - return "projects/{project}/secrets/{secret}".format(project=project, secret=secret, ) - - @staticmethod - def parse_secret_path(path: str) -> Dict[str,str]: - """Parses a secret path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def secret_version_path(project: str,secret: str,version: str,) -> str: - """Returns a fully-qualified secret_version string.""" - return "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) - - @staticmethod - def parse_secret_version_path(path: str) -> Dict[str,str]: - """Parses a secret_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_path(project: str,location: str,service: str,) -> str: - """Returns a fully-qualified service string.""" - return "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, 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.+?)/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 {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ServicesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the services 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, ServicesTransport]): 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() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ServicesTransport): - # transport is a ServicesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_service(self, - request: Union[gcr_service.CreateServiceRequest, dict] = None, - *, - parent: str = None, - service: gcr_service.Service = None, - service_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new Service in a given project and - location. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_create_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.CreateServiceRequest( - parent="parent_value", - service_id="service_id_value", - ) - - # Make the request - operation = client.create_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.CreateServiceRequest, dict]): - The request object. Request message for creating a - Service. - parent (str): - Required. The location and project in - which this service should be created. - Format: - projects/{projectnumber}/locations/{location} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service (google.cloud.run_v2.types.Service): - Required. The Service instance to - create. - - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_id (str): - Required. The unique identifier for the Service. The - name of the service becomes - {parent}/services/{service_id}. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of - configurations and revision templates which implement - a network service. Service exists to provide a - singular abstraction which can be access controlled, - reasoned about, and which encapsulates software - lifecycle decisions such as rollout policy and team - resource ownership. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 gcr_service.CreateServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcr_service.CreateServiceRequest): - request = gcr_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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcr_service.Service, - metadata_type=gcr_service.Service, - ) - - # Done; return the response. - return response - - def get_service(self, - request: Union[service.GetServiceRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.Service: - r"""Gets information about a Service. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_get_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.GetServiceRequest( - name="name_value", - ) - - # Make the request - response = client.get_service(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.GetServiceRequest, dict]): - The request object. Request message for obtaining a - Service by its full name. - name (str): - Required. The full name of the - Service. Format: - projects/{projectnumber}/locations/{location}/services/{service} - - 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.run_v2.types.Service: - Service acts as a top-level container - that manages a set of configurations and - revision templates which implement a - network service. Service exists to - provide a singular abstraction which can - be access controlled, reasoned about, - and which encapsulates software - lifecycle decisions such as rollout - policy and team resource ownership. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a service.GetServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.GetServiceRequest): - request = 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 list_services(self, - request: Union[service.ListServicesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServicesPager: - r"""List Services. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_list_services(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.ListServicesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_services(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.run_v2.types.ListServicesRequest, dict]): - The request object. Request message for retrieving a - list of Services. - parent (str): - Required. The location and project to - list resources on. Location must be a - valid GCP region, and may not be the "-" - wildcard. Format: - projects/{projectnumber}/locations/{location} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.run_v2.services.services.pagers.ListServicesPager: - Response message containing a list of - Services. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a service.ListServicesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.ListServicesRequest): - request = 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 update_service(self, - request: Union[gcr_service.UpdateServiceRequest, dict] = None, - *, - service: gcr_service.Service = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates a Service. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_update_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.UpdateServiceRequest( - ) - - # Make the request - operation = client.update_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.UpdateServiceRequest, dict]): - The request object. Request message for updating a - service. - service (google.cloud.run_v2.types.Service): - Required. The Service to be updated. - 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): - The list of fields to be updated. - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of - configurations and revision templates which implement - a network service. Service exists to provide a - singular abstraction which can be access controlled, - reasoned about, and which encapsulates software - lifecycle decisions such as rollout policy and team - resource ownership. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service, 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 gcr_service.UpdateServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcr_service.UpdateServiceRequest): - request = gcr_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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcr_service.Service, - metadata_type=gcr_service.Service, - ) - - # Done; return the response. - return response - - def delete_service(self, - request: Union[service.DeleteServiceRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a Service. - This will cause the Service to stop serving traffic and - will delete all revisions. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_delete_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.DeleteServiceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.run_v2.types.DeleteServiceRequest, dict]): - The request object. Request message to delete a Service - by its full name. - name (str): - Required. The full name of the - Service. Format: - projects/{projectnumber}/locations/{location}/services/{service} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.run_v2.types.Service` Service acts as a top-level container that manages a set of - configurations and revision templates which implement - a network service. Service exists to provide a - singular abstraction which can be access controlled, - reasoned about, and which encapsulates software - lifecycle decisions such as rollout policy and team - resource ownership. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a service.DeleteServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.DeleteServiceRequest): - request = 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - service.Service, - metadata_type=service.Service, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Get the IAM Access Control policy currently in effect - for the given Cloud Run Service. This result does not - include any inherited policies. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_get_iam_policy(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - 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: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ 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: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM Access control policy for the specified - Service. Overwrites any existing policy. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_set_iam_policy(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - 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: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ 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: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns permissions that a caller has on the - specified Project. - There are no permissions required for making this API - call. - - .. code-block:: python - - from google.cloud import run_v2 - - def sample_test_iam_permissions(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value_1', 'permissions_value_2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - 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-run", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServicesClient", -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/pagers.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/pagers.py deleted file mode 100644 index b411cdd..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/services/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.run_v2.types import service - - -class ListServicesPager: - """A pager for iterating through ``list_services`` requests. - - This class thinly wraps an initial - :class:`google.cloud.run_v2.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.run_v2.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[..., service.ListServicesResponse], - request: service.ListServicesRequest, - response: 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.run_v2.types.ListServicesRequest): - The initial request object. - response (google.cloud.run_v2.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 = 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[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.run_v2.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.run_v2.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[service.ListServicesResponse]], - request: service.ListServicesRequest, - response: 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.run_v2.types.ListServicesRequest): - The initial request object. - response (google.cloud.run_v2.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 = 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[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) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/__init__.py deleted file mode 100644 index f5bea72..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ServicesTransport -from .grpc import ServicesGrpcTransport -from .grpc_asyncio import ServicesGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServicesTransport]] -_transport_registry['grpc'] = ServicesGrpcTransport -_transport_registry['grpc_asyncio'] = ServicesGrpcAsyncIOTransport - -__all__ = ( - 'ServicesTransport', - 'ServicesGrpcTransport', - 'ServicesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/base.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/base.py deleted file mode 100644 index f0ebc1b..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/base.py +++ /dev/null @@ -1,270 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.run_v2.types import service -from google.cloud.run_v2.types import service as gcr_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-run', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class ServicesTransport(abc.ABC): - """Abstract transport class for Services.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'run.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_service: gapic_v1.method.wrap_method( - self.create_service, - default_timeout=15.0, - client_info=client_info, - ), - self.get_service: gapic_v1.method.wrap_method( - self.get_service, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.list_services: gapic_v1.method.wrap_method( - self.list_services, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.update_service: gapic_v1.method.wrap_method( - self.update_service, - default_timeout=15.0, - client_info=client_info, - ), - self.delete_service: gapic_v1.method.wrap_method( - self.delete_service, - default_timeout=10.0, - 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 operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_service(self) -> Callable[ - [gcr_service.CreateServiceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_service(self) -> Callable[ - [service.GetServiceRequest], - Union[ - service.Service, - Awaitable[service.Service] - ]]: - raise NotImplementedError() - - @property - def list_services(self) -> Callable[ - [service.ListServicesRequest], - Union[ - service.ListServicesResponse, - Awaitable[service.ListServicesResponse] - ]]: - raise NotImplementedError() - - @property - def update_service(self) -> Callable[ - [gcr_service.UpdateServiceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_service(self) -> Callable[ - [service.DeleteServiceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - 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() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ServicesTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc.py deleted file mode 100644 index e0ec942..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc.py +++ /dev/null @@ -1,475 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.run_v2.types import service -from google.cloud.run_v2.types import service as gcr_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import ServicesTransport, DEFAULT_CLIENT_INFO - - -class ServicesGrpcTransport(ServicesTransport): - """gRPC backend transport for Services. - - Cloud Run Service Control Plane API - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'run.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] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'run.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 operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_service(self) -> Callable[ - [gcr_service.CreateServiceRequest], - operations_pb2.Operation]: - r"""Return a callable for the create service method over gRPC. - - Creates a new Service in a given project and - location. - - Returns: - Callable[[~.CreateServiceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_service' not in self._stubs: - self._stubs['create_service'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Services/CreateService', - request_serializer=gcr_service.CreateServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_service'] - - @property - def get_service(self) -> Callable[ - [service.GetServiceRequest], - service.Service]: - r"""Return a callable for the get service method over gRPC. - - Gets information about 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.run.v2.Services/GetService', - request_serializer=service.GetServiceRequest.serialize, - response_deserializer=service.Service.deserialize, - ) - return self._stubs['get_service'] - - @property - def list_services(self) -> Callable[ - [service.ListServicesRequest], - service.ListServicesResponse]: - r"""Return a callable for the list services method over gRPC. - - List Services. - - 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.run.v2.Services/ListServices', - request_serializer=service.ListServicesRequest.serialize, - response_deserializer=service.ListServicesResponse.deserialize, - ) - return self._stubs['list_services'] - - @property - def update_service(self) -> Callable[ - [gcr_service.UpdateServiceRequest], - operations_pb2.Operation]: - r"""Return a callable for the update service method over gRPC. - - Updates a Service. - - Returns: - Callable[[~.UpdateServiceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_service' not in self._stubs: - self._stubs['update_service'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Services/UpdateService', - request_serializer=gcr_service.UpdateServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_service'] - - @property - def delete_service(self) -> Callable[ - [service.DeleteServiceRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete service method over gRPC. - - Deletes a Service. - This will cause the Service to stop serving traffic and - will delete all revisions. - - Returns: - Callable[[~.DeleteServiceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_service' not in self._stubs: - self._stubs['delete_service'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Services/DeleteService', - request_serializer=service.DeleteServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_service'] - - @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. - - Get the IAM Access Control policy currently in effect - for the given Cloud Run Service. This result does not - include any inherited policies. - - 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.run.v2.Services/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 Access control policy for the specified - Service. Overwrites any existing policy. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Services/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. - - Returns permissions that a caller has on the - specified Project. - There are no permissions required for making this API - call. - - 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.run.v2.Services/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() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ServicesGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc_asyncio.py deleted file mode 100644 index 86b95d0..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/services/services/transports/grpc_asyncio.py +++ /dev/null @@ -1,474 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.run_v2.types import service -from google.cloud.run_v2.types import service as gcr_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import ServicesTransport, DEFAULT_CLIENT_INFO -from .grpc import ServicesGrpcTransport - - -class ServicesGrpcAsyncIOTransport(ServicesTransport): - """gRPC AsyncIO backend transport for Services. - - Cloud Run Service Control Plane API - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'run.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 = 'run.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] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_service(self) -> Callable[ - [gcr_service.CreateServiceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create service method over gRPC. - - Creates a new Service in a given project and - location. - - Returns: - Callable[[~.CreateServiceRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_service' not in self._stubs: - self._stubs['create_service'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Services/CreateService', - request_serializer=gcr_service.CreateServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_service'] - - @property - def get_service(self) -> Callable[ - [service.GetServiceRequest], - Awaitable[service.Service]]: - r"""Return a callable for the get service method over gRPC. - - Gets information about 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.run.v2.Services/GetService', - request_serializer=service.GetServiceRequest.serialize, - response_deserializer=service.Service.deserialize, - ) - return self._stubs['get_service'] - - @property - def list_services(self) -> Callable[ - [service.ListServicesRequest], - Awaitable[service.ListServicesResponse]]: - r"""Return a callable for the list services method over gRPC. - - List Services. - - 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.run.v2.Services/ListServices', - request_serializer=service.ListServicesRequest.serialize, - response_deserializer=service.ListServicesResponse.deserialize, - ) - return self._stubs['list_services'] - - @property - def update_service(self) -> Callable[ - [gcr_service.UpdateServiceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update service method over gRPC. - - Updates a Service. - - Returns: - Callable[[~.UpdateServiceRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_service' not in self._stubs: - self._stubs['update_service'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Services/UpdateService', - request_serializer=gcr_service.UpdateServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_service'] - - @property - def delete_service(self) -> Callable[ - [service.DeleteServiceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete service method over gRPC. - - Deletes a Service. - This will cause the Service to stop serving traffic and - will delete all revisions. - - Returns: - Callable[[~.DeleteServiceRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_service' not in self._stubs: - self._stubs['delete_service'] = self.grpc_channel.unary_unary( - '/google.cloud.run.v2.Services/DeleteService', - request_serializer=service.DeleteServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_service'] - - @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. - - Get the IAM Access Control policy currently in effect - for the given Cloud Run Service. This result does not - include any inherited policies. - - 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.run.v2.Services/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 Access control policy for the specified - Service. Overwrites any existing policy. - - 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.run.v2.Services/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. - - Returns permissions that a caller has on the - specified Project. - There are no permissions required for making this API - call. - - 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.run.v2.Services/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__ = ( - 'ServicesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/run_v2/types/__init__.py deleted file mode 100644 index e6ddcc2..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/types/__init__.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .condition import ( - Condition, -) -from .k8s_min import ( - CloudSqlInstance, - Container, - ContainerPort, - EnvVar, - EnvVarSource, - ResourceRequirements, - SecretKeySelector, - SecretVolumeSource, - VersionToPath, - Volume, - VolumeMount, -) -from .revision import ( - DeleteRevisionRequest, - GetRevisionRequest, - ListRevisionsRequest, - ListRevisionsResponse, - Revision, -) -from .revision_template import ( - RevisionTemplate, -) -from .service import ( - CreateServiceRequest, - DeleteServiceRequest, - GetServiceRequest, - ListServicesRequest, - ListServicesResponse, - Service, - UpdateServiceRequest, -) -from .traffic_target import ( - TrafficTarget, - TrafficTargetStatus, - TrafficTargetAllocationType, -) -from .vendor_settings import ( - BinaryAuthorization, - RevisionScaling, - VpcAccess, - ExecutionEnvironment, - IngressTraffic, -) - -__all__ = ( - 'Condition', - 'CloudSqlInstance', - 'Container', - 'ContainerPort', - 'EnvVar', - 'EnvVarSource', - 'ResourceRequirements', - 'SecretKeySelector', - 'SecretVolumeSource', - 'VersionToPath', - 'Volume', - 'VolumeMount', - 'DeleteRevisionRequest', - 'GetRevisionRequest', - 'ListRevisionsRequest', - 'ListRevisionsResponse', - 'Revision', - 'RevisionTemplate', - 'CreateServiceRequest', - 'DeleteServiceRequest', - 'GetServiceRequest', - 'ListServicesRequest', - 'ListServicesResponse', - 'Service', - 'UpdateServiceRequest', - 'TrafficTarget', - 'TrafficTargetStatus', - 'TrafficTargetAllocationType', - 'BinaryAuthorization', - 'RevisionScaling', - 'VpcAccess', - 'ExecutionEnvironment', - 'IngressTraffic', -) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/condition.py b/owl-bot-staging/v2/google/cloud/run_v2/types/condition.py deleted file mode 100644 index 15c76f0..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/types/condition.py +++ /dev/null @@ -1,214 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.run.v2', - manifest={ - 'Condition', - }, -) - - -class Condition(proto.Message): - r"""Defines a status condition for a resource. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - type_ (str): - type is used to communicate the status of the reconciliation - process. See also: - https://github.com/knative/serving/blob/main/docs/spec/errors.md#error-conditions-and-reporting - Types common to all resources include: - - - "Ready": True when the Resource is ready. - state (google.cloud.run_v2.types.Condition.State): - State of the condition. - message (str): - Human readable message indicating details - about the current status. - last_transition_time (google.protobuf.timestamp_pb2.Timestamp): - Last time the condition transitioned from one - status to another. - severity (google.cloud.run_v2.types.Condition.Severity): - How to interpret failures of this condition, - one of Error, Warning, Info - reason (google.cloud.run_v2.types.Condition.CommonReason): - A common (service-level) reason for this - condition. - - This field is a member of `oneof`_ ``reasons``. - internal_reason (google.cloud.run_v2.types.Condition.InternalReason): - A reason for the internal condition. - - This field is a member of `oneof`_ ``reasons``. - domain_mapping_reason (google.cloud.run_v2.types.Condition.DomainMappingReason): - A reason for the domain mapping condition. - - This field is a member of `oneof`_ ``reasons``. - revision_reason (google.cloud.run_v2.types.Condition.RevisionReason): - A reason for the revision condition. - - This field is a member of `oneof`_ ``reasons``. - execution_reason (google.cloud.run_v2.types.Condition.ExecutionReason): - A reason for the execution condition. - - This field is a member of `oneof`_ ``reasons``. - """ - class State(proto.Enum): - r"""Represents the possible Condition states.""" - STATE_UNSPECIFIED = 0 - CONDITION_PENDING = 1 - CONDITION_RECONCILING = 2 - CONDITION_FAILED = 3 - CONDITION_SUCCEEDED = 4 - - class Severity(proto.Enum): - r"""Represents the severity of the condition failures.""" - SEVERITY_UNSPECIFIED = 0 - ERROR = 1 - WARNING = 2 - INFO = 3 - - class CommonReason(proto.Enum): - r"""Reasons common to all types of conditions.""" - COMMON_REASON_UNDEFINED = 0 - UNKNOWN = 1 - ROUTE_MISSING = 2 - REVISION_FAILED = 3 - PROGRESS_DEADLINE_EXCEEDED = 4 - BUILD_STEP_FAILED = 5 - CONTAINER_MISSING = 6 - CONTAINER_PERMISSION_DENIED = 7 - CONTAINER_IMAGE_UNAUTHORIZED = 8 - CONTAINER_IMAGE_AUTHORIZATION_CHECK_FAILED = 9 - ENCRYPTION_KEY_PERMISSION_DENIED = 10 - ENCRYPTION_KEY_CHECK_FAILED = 11 - SECRETS_ACCESS_CHECK_FAILED = 12 - WAITING_FOR_OPERATION = 13 - IMMEDIATE_RETRY = 14 - POSTPONED_RETRY = 15 - - class InternalReason(proto.Enum): - r"""Reasons applicable to internal resources not exposed to - users. These will surface in Service.conditions, and could be - useful for further diagnosis. - """ - INTERNAL_REASON_UNDEFINED = 0 - CONFLICTING_REVISION_NAME = 1 - REVISION_MISSING = 2 - CONFIGURATION_MISSING = 3 - ASSIGNING_TRAFFIC = 4 - UPDATING_INGRESS_TRAFFIC_ALLOWED = 5 - REVISION_ORG_POLICY_VIOLATION = 6 - ENABLING_GCFV2_URI_SUPPORT = 7 - - class DomainMappingReason(proto.Enum): - r"""Reasons specific to DomainMapping resource.""" - DOMAIN_MAPPING_REASON_UNDEFINED = 0 - ROUTE_NOT_READY = 1 - PERMISSION_DENIED = 2 - CERTIFICATE_ALREADY_EXISTS = 3 - MAPPING_ALREADY_EXISTS = 4 - CERTIFICATE_PENDING = 5 - CERTIFICATE_FAILED = 6 - - class RevisionReason(proto.Enum): - r"""Reasons specific to Revision resource.""" - REVISION_REASON_UNDEFINED = 0 - PENDING = 1 - RESERVE = 2 - RETIRED = 3 - RETIRING = 4 - RECREATING = 5 - HEALTH_CHECK_CONTAINER_ERROR = 6 - CUSTOMIZED_PATH_RESPONSE_PENDING = 7 - MIN_INSTANCES_NOT_PROVISIONED = 8 - ACTIVE_REVISION_LIMIT_REACHED = 9 - NO_DEPLOYMENT = 10 - HEALTH_CHECK_SKIPPED = 11 - - class ExecutionReason(proto.Enum): - r"""Reasons specific to Execution resource.""" - EXECUTION_REASON_UNDEFINED = 0 - JOB_STATUS_SERVICE_POLLING_ERROR = 1 - NON_ZERO_EXIT_CODE = 2 - - type_ = proto.Field( - proto.STRING, - number=1, - ) - state = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - message = proto.Field( - proto.STRING, - number=3, - ) - last_transition_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - severity = proto.Field( - proto.ENUM, - number=5, - enum=Severity, - ) - reason = proto.Field( - proto.ENUM, - number=6, - oneof='reasons', - enum=CommonReason, - ) - internal_reason = proto.Field( - proto.ENUM, - number=7, - oneof='reasons', - enum=InternalReason, - ) - domain_mapping_reason = proto.Field( - proto.ENUM, - number=8, - oneof='reasons', - enum=DomainMappingReason, - ) - revision_reason = proto.Field( - proto.ENUM, - number=9, - oneof='reasons', - enum=RevisionReason, - ) - execution_reason = proto.Field( - proto.ENUM, - number=11, - oneof='reasons', - enum=ExecutionReason, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/k8s_min.py b/owl-bot-staging/v2/google/cloud/run_v2/types/k8s_min.py deleted file mode 100644 index fab6a76..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/types/k8s_min.py +++ /dev/null @@ -1,477 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.run.v2', - manifest={ - 'Container', - 'ResourceRequirements', - 'EnvVar', - 'EnvVarSource', - 'SecretKeySelector', - 'ContainerPort', - 'VolumeMount', - 'Volume', - 'SecretVolumeSource', - 'VersionToPath', - 'CloudSqlInstance', - }, -) - - -class Container(proto.Message): - r"""A single application container. - This specifies both the container to run, the command to run in - the container and the arguments to supply to it. - Note that additional arguments may be supplied by the system to - the container at runtime. - - Attributes: - name (str): - Name of the container specified as a DNS_LABEL. - image (str): - Required. URL of the Container image in - Google Container Registry or Docker More info: - https://kubernetes.io/docs/concepts/containers/images - command (Sequence[str]): - Entrypoint array. Not executed within a shell. The docker - image's ENTRYPOINT is used if this is not provided. Variable - references $(VAR_NAME) are expanded using the container's - environment. If a variable cannot be resolved, the reference - in the input string will be unchanged. The $(VAR_NAME) - syntax can be escaped with a double $$, ie: $$(VAR_NAME). - Escaped references will never be expanded, regardless of - whether the variable exists or not. More info: - https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell - args (Sequence[str]): - Arguments to the entrypoint. The docker image's CMD is used - if this is not provided. Variable references $(VAR_NAME) are - expanded using the container's environment. If a variable - cannot be resolved, the reference in the input string will - be unchanged. The $(VAR_NAME) syntax can be escaped with a - double $$, ie: $$(VAR_NAME). Escaped references will never - be expanded, regardless of whether the variable exists or - not. More info: - https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell - env (Sequence[google.cloud.run_v2.types.EnvVar]): - List of environment variables to set in the - container. - resources (google.cloud.run_v2.types.ResourceRequirements): - Compute Resource requirements by this - container. More info: - https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources - ports (Sequence[google.cloud.run_v2.types.ContainerPort]): - List of ports to expose from the container. - Only a single port can be specified. The - specified ports must be listening on all - interfaces (0.0.0.0) within the container to be - accessible. - If omitted, a port number will be chosen and - passed to the container through the PORT - environment variable for the container to listen - on. - volume_mounts (Sequence[google.cloud.run_v2.types.VolumeMount]): - Volume to mount into the container's - filesystem. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - image = proto.Field( - proto.STRING, - number=2, - ) - command = proto.RepeatedField( - proto.STRING, - number=3, - ) - args = proto.RepeatedField( - proto.STRING, - number=4, - ) - env = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='EnvVar', - ) - resources = proto.Field( - proto.MESSAGE, - number=6, - message='ResourceRequirements', - ) - ports = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ContainerPort', - ) - volume_mounts = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='VolumeMount', - ) - - -class ResourceRequirements(proto.Message): - r"""ResourceRequirements describes the compute resource - requirements. - - Attributes: - limits (Mapping[str, str]): - Only memory and CPU are supported. Note: The - only supported values for CPU are '1', '2', and - '4'. Setting 4 CPU requires at least 2Gi of - memory. - The values of the map is string form of the - 'quantity' k8s type: - https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go - cpu_idle (bool): - Determines whether CPU should be throttled or - not outside of requests. - """ - - limits = proto.MapField( - proto.STRING, - proto.STRING, - number=1, - ) - cpu_idle = proto.Field( - proto.BOOL, - number=2, - ) - - -class EnvVar(proto.Message): - r"""EnvVar represents an environment variable present in a - Container. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. Name of the environment variable. Must be a - C_IDENTIFIER, and mnay not exceed 32768 characters. - value (str): - Variable references $(VAR_NAME) are expanded using the - previous defined environment variables in the container and - any route environment variables. If a variable cannot be - resolved, the reference in the input string will be - unchanged. The $(VAR_NAME) syntax can be escaped with a - double $$, ie: $$(VAR_NAME). Escaped references will never - be expanded, regardless of whether the variable exists or - not. Defaults to "", and the maximum length is 32768 bytes. - - This field is a member of `oneof`_ ``values``. - value_source (google.cloud.run_v2.types.EnvVarSource): - Source for the environment variable's value. - - This field is a member of `oneof`_ ``values``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - value = proto.Field( - proto.STRING, - number=2, - oneof='values', - ) - value_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='values', - message='EnvVarSource', - ) - - -class EnvVarSource(proto.Message): - r"""EnvVarSource represents a source for the value of an EnvVar. - - Attributes: - secret_key_ref (google.cloud.run_v2.types.SecretKeySelector): - Selects a secret and a specific version from - Cloud Secret Manager. - """ - - secret_key_ref = proto.Field( - proto.MESSAGE, - number=1, - message='SecretKeySelector', - ) - - -class SecretKeySelector(proto.Message): - r"""SecretEnvVarSource represents a source for the value of an - EnvVar. - - Attributes: - secret (str): - Required. The name of the secret in Cloud Secret Manager. - Format: {secret_name} if the secret is in the same project. - projects/{project}/secrets/{secret_name} if the secret is in - a different project. - version (str): - The Cloud Secret Manager secret version. - Can be 'latest' for the latest value or an - integer for a specific version. - """ - - secret = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.STRING, - number=2, - ) - - -class ContainerPort(proto.Message): - r"""ContainerPort represents a network port in a single - container. - - Attributes: - name (str): - If specified, used to specify which protocol - to use. Allowed values are "http1" and "h2c". - container_port (int): - Port number the container listens on. This must be a valid - TCP port number, 0 < container_port < 65536. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - container_port = proto.Field( - proto.INT32, - number=3, - ) - - -class VolumeMount(proto.Message): - r"""VolumeMount describes a mounting of a Volume within a - container. - - Attributes: - name (str): - Required. This must match the Name of a - Volume. - mount_path (str): - Required. Path within the container at which the volume - should be mounted. Must not contain ':'. For Cloud SQL - volumes, it can be left empty, or must otherwise be - ``/cloudsql``. All instances defined in the Volume will be - available as ``/cloudsql/[instance]``. For more information - on Cloud SQL volumes, visit - https://cloud.google.com/sql/docs/mysql/connect-run - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - mount_path = proto.Field( - proto.STRING, - number=3, - ) - - -class Volume(proto.Message): - r"""Volume represents a named volume in a container. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. Volume's name. - secret (google.cloud.run_v2.types.SecretVolumeSource): - Secret represents a secret that should - populate this volume. More info: - https://kubernetes.io/docs/concepts/storage/volumes#secret - - This field is a member of `oneof`_ ``volume_type``. - cloud_sql_instance (google.cloud.run_v2.types.CloudSqlInstance): - For Cloud SQL volumes, contains the specific - instances that should be mounted. Visit - https://cloud.google.com/sql/docs/mysql/connect-run - for more information on how to connect Cloud SQL - and Cloud Run. - - This field is a member of `oneof`_ ``volume_type``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - secret = proto.Field( - proto.MESSAGE, - number=2, - oneof='volume_type', - message='SecretVolumeSource', - ) - cloud_sql_instance = proto.Field( - proto.MESSAGE, - number=3, - oneof='volume_type', - message='CloudSqlInstance', - ) - - -class SecretVolumeSource(proto.Message): - r"""The secret's value will be presented as the content of a file - whose name is defined in the item path. If no items are defined, - the name of the file is the secret. - - Attributes: - secret (str): - Required. The name of the secret in Cloud - Secret Manager. Format: {secret} if the secret - is in the same project. - projects/{project}/secrets/{secret} if the - secret is in a different project. - items (Sequence[google.cloud.run_v2.types.VersionToPath]): - If unspecified, the volume will expose a file whose name is - the secret, relative to VolumeMount.mount_path. If - specified, the key will be used as the version to fetch from - Cloud Secret Manager and the path will be the name of the - file exposed in the volume. When items are defined, they - must specify a path and a version. - default_mode (int): - Integer representation of mode bits to use on created files - by default. Must be a value between 0000 and 0777 (octal), - defaulting to 0644. Directories within the path are not - affected by this setting. - - Notes - - - Internally, a umask of 0222 will be applied to any - non-zero value. - - This is an integer representation of the mode bits. So, - the octal integer value should look exactly as the chmod - numeric notation with a leading zero. Some examples: for - chmod 777 (a=rwx), set to 0777 (octal) or 511 (base-10). - For chmod 640 (u=rw,g=r), set to 0640 (octal) or 416 - (base-10). For chmod 755 (u=rwx,g=rx,o=rx), set to 0755 - (octal) or 493 (base-10). - - This might be in conflict with other options that affect - the file mode, like fsGroup, and the result can be other - mode bits set. - - This might be in conflict with other options that affect the - file mode, like fsGroup, and as a result, other mode bits - could be set. - """ - - secret = proto.Field( - proto.STRING, - number=1, - ) - items = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='VersionToPath', - ) - default_mode = proto.Field( - proto.INT32, - number=3, - ) - - -class VersionToPath(proto.Message): - r"""VersionToPath maps a specific version of a secret to a relative file - to mount to, relative to VolumeMount's mount_path. - - Attributes: - path (str): - Required. The relative path of the secret in - the container. - version (str): - The Cloud Secret Manager secret version. - Can be 'latest' for the latest value or an - integer for a specific version. - mode (int): - Integer octal mode bits to use on this file, must be a value - between 01 and 0777 (octal). If 0 or not set, the Volume's - default mode will be used. - - Notes - - - Internally, a umask of 0222 will be applied to any - non-zero value. - - This is an integer representation of the mode bits. So, - the octal integer value should look exactly as the chmod - numeric notation with a leading zero. Some examples: for - chmod 777 (a=rwx), set to 0777 (octal) or 511 (base-10). - For chmod 640 (u=rw,g=r), set to 0640 (octal) or 416 - (base-10). For chmod 755 (u=rwx,g=rx,o=rx), set to 0755 - (octal) or 493 (base-10). - - This might be in conflict with other options that affect - the file mode, like fsGroup, and the result can be other - mode bits set. - """ - - path = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.STRING, - number=2, - ) - mode = proto.Field( - proto.INT32, - number=3, - ) - - -class CloudSqlInstance(proto.Message): - r"""Represents a specific Cloud SQL instance. - - Attributes: - connections (Sequence[str]): - The Cloud SQL instance connection names, as - can be found in - https://console.cloud.google.com/sql/instances. - Visit - https://cloud.google.com/sql/docs/mysql/connect-run - for more information on how to connect Cloud SQL - and Cloud Run. Format: - {project}:{location}:{instance} - """ - - connections = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/revision.py b/owl-bot-staging/v2/google/cloud/run_v2/types/revision.py deleted file mode 100644 index 1fc0fee..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/types/revision.py +++ /dev/null @@ -1,388 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.api import launch_stage_pb2 # type: ignore -from google.cloud.run_v2.types import condition -from google.cloud.run_v2.types import k8s_min -from google.cloud.run_v2.types import vendor_settings -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.run.v2', - manifest={ - 'GetRevisionRequest', - 'ListRevisionsRequest', - 'ListRevisionsResponse', - 'DeleteRevisionRequest', - 'Revision', - }, -) - - -class GetRevisionRequest(proto.Message): - r"""Request message for obtaining a Revision by its full name. - - Attributes: - name (str): - Required. The full name of the Revision. - Format: - projects/{project}/locations/{location}/services/{service}/revisions/{revision} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListRevisionsRequest(proto.Message): - r"""Request message for retrieving a list of Revisions. - - Attributes: - parent (str): - Required. The Service from which the - Revisions should be listed. To list all - Revisions across Services, use "-" instead of - Service name. Format: - projects/{project}/locations/{location}/services/{service} - page_size (int): - Maximum number of revisions to return in this - call. - page_token (str): - A page token received from a previous call to - ListRevisions. All other parameters must match. - show_deleted (bool): - If true, returns deleted (but unexpired) - resources along with active ones. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - show_deleted = proto.Field( - proto.BOOL, - number=4, - ) - - -class ListRevisionsResponse(proto.Message): - r"""Response message containing a list of Revisions. - - Attributes: - revisions (Sequence[google.cloud.run_v2.types.Revision]): - The resulting list of Revisions. - next_page_token (str): - A token indicating there are more items than page_size. Use - it in the next ListRevisions request to continue. - """ - - @property - def raw_page(self): - return self - - revisions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Revision', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteRevisionRequest(proto.Message): - r"""Request message for deleting a retired Revision. - Revision lifecycle is usually managed by making changes to the - parent Service. Only retired revisions can be deleted with this - API. - - Attributes: - name (str): - Required. The name of the Revision to delete. - Format: - projects/{project}/locations/{location}/services/{service}/revisions/{revision} - validate_only (bool): - Indicates that the request should be - validated without actually deleting any - resources. - etag (str): - A system-generated fingerprint for this - version of the resource. This may be used to - detect modification conflict during updates. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - validate_only = proto.Field( - proto.BOOL, - number=2, - ) - etag = proto.Field( - proto.STRING, - number=3, - ) - - -class Revision(proto.Message): - r"""A Revision is an immutable snapshot of code and - configuration. A Revision references a container image. - Revisions are only created by updates to its parent Service. - - Attributes: - name (str): - Output only. The unique name of this - Revision. - uid (str): - Output only. Server assigned unique - identifier for the Revision. The value is a - UUID4 string and guaranteed to remain unchanged - until the resource is deleted. - generation (int): - Output only. A number that monotonically - increases every time the user modifies the - desired state. - labels (Mapping[str, str]): - KRM-style labels for the resource. - User-provided labels are shared with Google's - billing system, so they can be used to filter, - or break down billing charges by team, - component, environment, state, etc. For more - information, visit - https://cloud.google.com/resource-manager/docs/creating-managing-labels - or - https://cloud.google.com/run/docs/configuring/labels - Cloud Run will populate some labels with - 'run.googleapis.com' or 'serving.knative.dev' - namespaces. Those labels are read-only, and user - changes will not be preserved. - annotations (Mapping[str, str]): - KRM-style annotations for the resource. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The creation time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last-modified time. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. For a deleted resource, the - deletion time. It is only populated as a - response to a Delete request. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. For a deleted resource, the time - after which it will be permamently deleted. It - is only populated as a response to a Delete - request. - launch_stage (google.api.launch_stage_pb2.LaunchStage): - Set the launch stage to a preview stage on write to allow - use of preview features in that stage. On read, describes - whether the resource uses preview features. Launch Stages - are defined at `Google Cloud Platform Launch - Stages `__. - service (str): - Output only. The name of the parent service. - scaling (google.cloud.run_v2.types.RevisionScaling): - Scaling settings for this revision. - vpc_access (google.cloud.run_v2.types.VpcAccess): - VPC Access configuration for this Revision. - For more information, visit - https://cloud.google.com/run/docs/configuring/connecting-vpc. - container_concurrency (int): - Sets the maximum number of requests that each - serving instance can receive. - timeout (google.protobuf.duration_pb2.Duration): - Max allowed time for an instance to respond - to a request. - service_account (str): - Email address of the IAM service account - associated with the revision of the service. The - service account represents the identity of the - running revision, and determines what - permissions the revision has. - containers (Sequence[google.cloud.run_v2.types.Container]): - Holds the single container that defines the - unit of execution for this Revision. - volumes (Sequence[google.cloud.run_v2.types.Volume]): - A list of Volumes to make available to - containers. - confidential (bool): - Indicates whether Confidential Cloud Run is - enabled in this Revision. - execution_environment (google.cloud.run_v2.types.ExecutionEnvironment): - The execution environment being used to host - this Revision. - encryption_key (str): - A reference to a customer managed encryption - key (CMEK) to use to encrypt this container - image. For more information, go to - https://cloud.google.com/run/docs/securing/using-cmek - reconciling (bool): - Output only. Indicates whether the resource's reconciliation - is still in progress. See comments in - ``Service.reconciling`` for additional information on - reconciliation process in Cloud Run. - conditions (Sequence[google.cloud.run_v2.types.Condition]): - Output only. The Condition of this Revision, - containing its readiness status, and detailed - error information in case it did not reach a - serving state. - observed_generation (int): - Output only. The generation of this Revision currently - serving traffic. See comments in ``reconciling`` for - additional information on reconciliation process in Cloud - Run. - log_uri (str): - Output only. The Google Console URI to obtain - logs for the Revision. - etag (str): - Output only. A system-generated fingerprint - for this version of the resource. May be used to - detect modification conflict during updates. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - uid = proto.Field( - proto.STRING, - number=2, - ) - generation = proto.Field( - proto.INT64, - number=3, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - annotations = proto.MapField( - proto.STRING, - 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, - ) - delete_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - expire_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - launch_stage = proto.Field( - proto.ENUM, - number=10, - enum=launch_stage_pb2.LaunchStage, - ) - service = proto.Field( - proto.STRING, - number=11, - ) - scaling = proto.Field( - proto.MESSAGE, - number=12, - message=vendor_settings.RevisionScaling, - ) - vpc_access = proto.Field( - proto.MESSAGE, - number=13, - message=vendor_settings.VpcAccess, - ) - container_concurrency = proto.Field( - proto.INT32, - number=14, - ) - timeout = proto.Field( - proto.MESSAGE, - number=15, - message=duration_pb2.Duration, - ) - service_account = proto.Field( - proto.STRING, - number=16, - ) - containers = proto.RepeatedField( - proto.MESSAGE, - number=17, - message=k8s_min.Container, - ) - volumes = proto.RepeatedField( - proto.MESSAGE, - number=18, - message=k8s_min.Volume, - ) - confidential = proto.Field( - proto.BOOL, - number=19, - ) - execution_environment = proto.Field( - proto.ENUM, - number=20, - enum=vendor_settings.ExecutionEnvironment, - ) - encryption_key = proto.Field( - proto.STRING, - number=21, - ) - reconciling = proto.Field( - proto.BOOL, - number=30, - ) - conditions = proto.RepeatedField( - proto.MESSAGE, - number=31, - message=condition.Condition, - ) - observed_generation = proto.Field( - proto.INT64, - number=32, - ) - log_uri = proto.Field( - proto.STRING, - number=33, - ) - etag = proto.Field( - proto.STRING, - number=99, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/revision_template.py b/owl-bot-staging/v2/google/cloud/run_v2/types/revision_template.py deleted file mode 100644 index 9480752..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/types/revision_template.py +++ /dev/null @@ -1,145 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.run_v2.types import k8s_min -from google.cloud.run_v2.types import vendor_settings -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.run.v2', - manifest={ - 'RevisionTemplate', - }, -) - - -class RevisionTemplate(proto.Message): - r"""RevisionTemplate describes the data a revision should have - when created from a template. - - Attributes: - revision (str): - The unique name for the revision. If this - field is omitted, it will be automatically - generated based on the Service name. - labels (Mapping[str, str]): - KRM-style labels for the resource. - annotations (Mapping[str, str]): - KRM-style annotations for the resource. - scaling (google.cloud.run_v2.types.RevisionScaling): - Scaling settings for this Revision. - vpc_access (google.cloud.run_v2.types.VpcAccess): - VPC Access configuration to use for this - Revision. For more information, visit - https://cloud.google.com/run/docs/configuring/connecting-vpc. - container_concurrency (int): - Sets the maximum number of requests that each - serving instance can receive. - timeout (google.protobuf.duration_pb2.Duration): - Max allowed time for an instance to respond - to a request. - service_account (str): - Email address of the IAM service account - associated with the revision of the service. The - service account represents the identity of the - running revision, and determines what - permissions the revision has. If not provided, - the revision will use the project's default - service account. - containers (Sequence[google.cloud.run_v2.types.Container]): - Holds the single container that defines the - unit of execution for this Revision. - volumes (Sequence[google.cloud.run_v2.types.Volume]): - A list of Volumes to make available to - containers. - confidential (bool): - Enables Confidential Cloud Run in Revisions - created using this template. - execution_environment (google.cloud.run_v2.types.ExecutionEnvironment): - The sandbox environment to host this - Revision. - encryption_key (str): - A reference to a customer managed encryption - key (CMEK) to use to encrypt this container - image. For more information, go to - https://cloud.google.com/run/docs/securing/using-cmek - """ - - revision = proto.Field( - proto.STRING, - number=1, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - annotations = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - scaling = proto.Field( - proto.MESSAGE, - number=4, - message=vendor_settings.RevisionScaling, - ) - vpc_access = proto.Field( - proto.MESSAGE, - number=6, - message=vendor_settings.VpcAccess, - ) - container_concurrency = proto.Field( - proto.INT32, - number=7, - ) - timeout = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - service_account = proto.Field( - proto.STRING, - number=9, - ) - containers = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=k8s_min.Container, - ) - volumes = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=k8s_min.Volume, - ) - confidential = proto.Field( - proto.BOOL, - number=12, - ) - execution_environment = proto.Field( - proto.ENUM, - number=13, - enum=vendor_settings.ExecutionEnvironment, - ) - encryption_key = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/service.py b/owl-bot-staging/v2/google/cloud/run_v2/types/service.py deleted file mode 100644 index a5c574e..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/types/service.py +++ /dev/null @@ -1,521 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.api import launch_stage_pb2 # type: ignore -from google.cloud.run_v2.types import condition -from google.cloud.run_v2.types import revision_template -from google.cloud.run_v2.types import traffic_target -from google.cloud.run_v2.types import vendor_settings -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.run.v2', - manifest={ - 'CreateServiceRequest', - 'UpdateServiceRequest', - 'ListServicesRequest', - 'ListServicesResponse', - 'GetServiceRequest', - 'DeleteServiceRequest', - 'Service', - }, -) - - -class CreateServiceRequest(proto.Message): - r"""Request message for creating a Service. - - Attributes: - parent (str): - Required. The location and project in which - this service should be created. Format: - projects/{projectnumber}/locations/{location} - service (google.cloud.run_v2.types.Service): - Required. The Service instance to create. - service_id (str): - Required. The unique identifier for the Service. The name of - the service becomes {parent}/services/{service_id}. - validate_only (bool): - Indicates that the request should be - validated and default values populated, without - persisting the request or creating any - resources. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - service = proto.Field( - proto.MESSAGE, - number=2, - message='Service', - ) - service_id = proto.Field( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateServiceRequest(proto.Message): - r"""Request message for updating a service. - - Attributes: - service (google.cloud.run_v2.types.Service): - Required. The Service to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - validate_only (bool): - Indicates that the request should be - validated and default values populated, without - persisting the request or updating any - resources. - allow_missing (bool): - If set to true, and if the Service does not - exist, it will create a new one. Caller must - have both create and update permissions for this - call if this is set to true. - """ - - service = proto.Field( - proto.MESSAGE, - number=1, - message='Service', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only = proto.Field( - proto.BOOL, - number=3, - ) - allow_missing = proto.Field( - proto.BOOL, - number=4, - ) - - -class ListServicesRequest(proto.Message): - r"""Request message for retrieving a list of Services. - - Attributes: - parent (str): - Required. The location and project to list - resources on. Location must be a valid GCP - region, and may not be the "-" wildcard. Format: - projects/{projectnumber}/locations/{location} - page_size (int): - Maximum number of Services to return in this - call. - page_token (str): - A page token received from a previous call to - ListServices. All other parameters must match. - show_deleted (bool): - If true, returns deleted (but unexpired) - resources along with active ones. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - show_deleted = proto.Field( - proto.BOOL, - number=4, - ) - - -class ListServicesResponse(proto.Message): - r"""Response message containing a list of Services. - - Attributes: - services (Sequence[google.cloud.run_v2.types.Service]): - The resulting list of Services. - next_page_token (str): - A token indicating there are more items than page_size. Use - it in the next ListServices request to continue. - """ - - @property - def raw_page(self): - return self - - services = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Service', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetServiceRequest(proto.Message): - r"""Request message for obtaining a Service by its full name. - - Attributes: - name (str): - Required. The full name of the Service. - Format: - projects/{projectnumber}/locations/{location}/services/{service} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteServiceRequest(proto.Message): - r"""Request message to delete a Service by its full name. - - Attributes: - name (str): - Required. The full name of the Service. - Format: - projects/{projectnumber}/locations/{location}/services/{service} - validate_only (bool): - Indicates that the request should be - validated without actually deleting any - resources. - etag (str): - A system-generated fingerprint for this - version of the resource. May be used to detect - modification conflict during updates. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - validate_only = proto.Field( - proto.BOOL, - number=2, - ) - etag = proto.Field( - proto.STRING, - number=3, - ) - - -class Service(proto.Message): - r"""Service acts as a top-level container that manages a set of - configurations and revision templates which implement a network - service. Service exists to provide a singular abstraction which - can be access controlled, reasoned about, and which encapsulates - software lifecycle decisions such as rollout policy and team - resource ownership. - - Attributes: - name (str): - The fully qualified name of this Service. In - CreateServiceRequest, this field is ignored, and instead - composed from CreateServiceRequest.parent and - CreateServiceRequest.service_id. - - Format: - projects/{project}/locations/{location}/services/{service_id} - description (str): - User-provided description of the Service. - This field currently has a 512-character limit. - uid (str): - Output only. Server assigned unique - identifier for the trigger. The value is a UUID4 - string and guaranteed to remain unchanged until - the resource is deleted. - generation (int): - Output only. A number that monotonically - increases every time the user modifies the - desired state. - labels (Mapping[str, str]): - Map of string keys and values that can be - used to organize and categorize objects. - User-provided labels are shared with Google's - billing system, so they can be used to filter, - or break down billing charges by team, - component, environment, state, etc. For more - information, visit - https://cloud.google.com/resource-manager/docs/creating-managing-labels - or - https://cloud.google.com/run/docs/configuring/labels - Cloud Run will populate some labels with - 'run.googleapis.com' or 'serving.knative.dev' - namespaces. Those labels are read-only, and user - changes will not be preserved. - annotations (Mapping[str, str]): - Unstructured key value map that may be set by - external tools to store and arbitrary metadata. - They are not queryable and should be preserved - when modifying objects. Cloud Run will populate - some annotations using 'run.googleapis.com' or - 'serving.knative.dev' namespaces. This field - follows Kubernetes annotations' namespacing, - limits, and rules. More info: - https://kubernetes.io/docs/user-guide/annotations - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The creation time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last-modified time. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The deletion time. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. For a deleted resource, the time - after which it will be permamently deleted. - creator (str): - Output only. Email address of the - authenticated creator. - last_modifier (str): - Output only. Email address of the last - authenticated modifier. - client (str): - Arbitrary identifier for the API client. - client_version (str): - Arbitrary version identifier for the API - client. - ingress (google.cloud.run_v2.types.IngressTraffic): - Provides the ingress settings for this Service. On output, - returns the currently observed ingress settings, or - INGRESS_TRAFFIC_UNSPECIFIED if no revision is active. - launch_stage (google.api.launch_stage_pb2.LaunchStage): - The launch stage as defined by `Google Cloud Platform Launch - Stages `__. - Cloud Run supports ``ALPHA``, ``BETA``, and ``GA``. If no - value is specified, GA is assumed. - binary_authorization (google.cloud.run_v2.types.BinaryAuthorization): - Settings for the Binary Authorization - feature. - template (google.cloud.run_v2.types.RevisionTemplate): - Required. The template used to create - revisions for this Service. - traffic (Sequence[google.cloud.run_v2.types.TrafficTarget]): - Specifies how to distribute traffic over a collection of - Revisions belonging to the Service. If traffic is empty or - not provided, defaults to 100% traffic to the latest - ``Ready`` Revision. - observed_generation (int): - Output only. The generation of this Service currently - serving traffic. See comments in ``reconciling`` for - additional information on reconciliation process in Cloud - Run. - terminal_condition (google.cloud.run_v2.types.Condition): - Output only. The Condition of this Service, containing its - readiness status, and detailed error information in case it - did not reach a serving state. See comments in - ``reconciling`` for additional information on reconciliation - process in Cloud Run. - conditions (Sequence[google.cloud.run_v2.types.Condition]): - Output only. The Conditions of all other associated - sub-resources. They contain additional diagnostics - information in case the Service does not reach its Serving - state. See comments in ``reconciling`` for additional - information on reconciliation process in Cloud Run. - latest_ready_revision (str): - Output only. Name of the latest revision that is serving - traffic. See comments in ``reconciling`` for additional - information on reconciliation process in Cloud Run. - latest_created_revision (str): - Output only. Name of the last created revision. See comments - in ``reconciling`` for additional information on - reconciliation process in Cloud Run. - traffic_statuses (Sequence[google.cloud.run_v2.types.TrafficTargetStatus]): - Output only. Detailed status information for corresponding - traffic targets. See comments in ``reconciling`` for - additional information on reconciliation process in Cloud - Run. - uri (str): - Output only. The main URI in which this - Service is serving traffic. - reconciling (bool): - Output only. Returns true if the Service is currently being - acted upon by the system to bring it into the desired state. - - When a new Service is created, or an existing one is - updated, Cloud Run will asynchronously perform all necessary - steps to bring the Service to the desired serving state. - This process is called reconciliation. While reconciliation - is in process, ``observed_generation``, - ``latest_ready_revison``, ``traffic_statuses``, and ``uri`` - will have transient values that might mismatch the intended - state: Once reconciliation is over (and this field is - false), there are two possible outcomes: reconciliation - succeeded and the serving state matches the Service, or - there was an error, and reconciliation failed. This state - can be found in ``terminal_condition.state``. - - If reconciliation succeeded, the following fields will - match: ``traffic`` and ``traffic_statuses``, - ``observed_generation`` and ``generation``, - ``latest_ready_revision`` and ``latest_created_revision``. - - If reconciliation failed, ``traffic_statuses``, - ``observed_generation``, and ``latest_ready_revision`` will - have the state of the last serving revision, or empty for - newly created Services. Additional information on the - failure can be found in ``terminal_condition`` and - ``conditions``. - etag (str): - Output only. A system-generated fingerprint - for this version of the resource. May be used to - detect modification conflict during updates. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - uid = proto.Field( - proto.STRING, - number=3, - ) - generation = proto.Field( - proto.INT64, - number=4, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - annotations = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - create_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - delete_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - expire_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - creator = proto.Field( - proto.STRING, - number=11, - ) - last_modifier = proto.Field( - proto.STRING, - number=12, - ) - client = proto.Field( - proto.STRING, - number=13, - ) - client_version = proto.Field( - proto.STRING, - number=14, - ) - ingress = proto.Field( - proto.ENUM, - number=15, - enum=vendor_settings.IngressTraffic, - ) - launch_stage = proto.Field( - proto.ENUM, - number=16, - enum=launch_stage_pb2.LaunchStage, - ) - binary_authorization = proto.Field( - proto.MESSAGE, - number=17, - message=vendor_settings.BinaryAuthorization, - ) - template = proto.Field( - proto.MESSAGE, - number=18, - message=revision_template.RevisionTemplate, - ) - traffic = proto.RepeatedField( - proto.MESSAGE, - number=19, - message=traffic_target.TrafficTarget, - ) - observed_generation = proto.Field( - proto.INT64, - number=30, - ) - terminal_condition = proto.Field( - proto.MESSAGE, - number=31, - message=condition.Condition, - ) - conditions = proto.RepeatedField( - proto.MESSAGE, - number=32, - message=condition.Condition, - ) - latest_ready_revision = proto.Field( - proto.STRING, - number=33, - ) - latest_created_revision = proto.Field( - proto.STRING, - number=34, - ) - traffic_statuses = proto.RepeatedField( - proto.MESSAGE, - number=35, - message=traffic_target.TrafficTargetStatus, - ) - uri = proto.Field( - proto.STRING, - number=36, - ) - reconciling = proto.Field( - proto.BOOL, - number=98, - ) - etag = proto.Field( - proto.STRING, - number=99, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/traffic_target.py b/owl-bot-staging/v2/google/cloud/run_v2/types/traffic_target.py deleted file mode 100644 index 875a209..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/types/traffic_target.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.run.v2', - manifest={ - 'TrafficTargetAllocationType', - 'TrafficTarget', - 'TrafficTargetStatus', - }, -) - - -class TrafficTargetAllocationType(proto.Enum): - r"""The type of instance allocation.""" - TRAFFIC_TARGET_ALLOCATION_TYPE_UNSPECIFIED = 0 - TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST = 1 - TRAFFIC_TARGET_ALLOCATION_TYPE_REVISION = 2 - - -class TrafficTarget(proto.Message): - r"""Holds a single traffic routing entry for the Service. - Allocations can be done to a specific Revision name, or pointing - to the latest Ready Revision. - - Attributes: - type_ (google.cloud.run_v2.types.TrafficTargetAllocationType): - The allocation type for this traffic target. - revision (str): - Revision to which to send this portion of - traffic, if traffic allocation is by revision. - percent (int): - Specifies percent of the traffic to this - Revision. This defaults to zero if unspecified. - tag (str): - Indicates a string to be part of the URI to - exclusively reference this target. - """ - - type_ = proto.Field( - proto.ENUM, - number=1, - enum='TrafficTargetAllocationType', - ) - revision = proto.Field( - proto.STRING, - number=2, - ) - percent = proto.Field( - proto.INT32, - number=3, - ) - tag = proto.Field( - proto.STRING, - number=4, - ) - - -class TrafficTargetStatus(proto.Message): - r"""Represents the observed state of a single ``TrafficTarget`` entry. - - Attributes: - type_ (google.cloud.run_v2.types.TrafficTargetAllocationType): - The allocation type for this traffic target. - revision (str): - Revision to which this traffic is sent. - percent (int): - Specifies percent of the traffic to this - Revision. - tag (str): - Indicates the string used in the URI to - exclusively reference this target. - uri (str): - Displays the target URI. - """ - - type_ = proto.Field( - proto.ENUM, - number=1, - enum='TrafficTargetAllocationType', - ) - revision = proto.Field( - proto.STRING, - number=2, - ) - percent = proto.Field( - proto.INT32, - number=3, - ) - tag = proto.Field( - proto.STRING, - number=4, - ) - uri = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/run_v2/types/vendor_settings.py b/owl-bot-staging/v2/google/cloud/run_v2/types/vendor_settings.py deleted file mode 100644 index 17a9a80..0000000 --- a/owl-bot-staging/v2/google/cloud/run_v2/types/vendor_settings.py +++ /dev/null @@ -1,131 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.run.v2', - manifest={ - 'IngressTraffic', - 'ExecutionEnvironment', - 'VpcAccess', - 'BinaryAuthorization', - 'RevisionScaling', - }, -) - - -class IngressTraffic(proto.Enum): - r"""Allowed ingress traffic for the Container.""" - INGRESS_TRAFFIC_UNSPECIFIED = 0 - INGRESS_TRAFFIC_ALL = 1 - INGRESS_TRAFFIC_INTERNAL_ONLY = 2 - INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER = 3 - - -class ExecutionEnvironment(proto.Enum): - r"""Alternatives for execution environments.""" - EXECUTION_ENVIRONMENT_UNSPECIFIED = 0 - EXECUTION_ENVIRONMENT_DEFAULT = 1 - EXECUTION_ENVIRONMENT_GEN2 = 2 - - -class VpcAccess(proto.Message): - r"""VPC Access settings. For more information on creating a VPC - Connector, visit - https://cloud.google.com/vpc/docs/configure-serverless-vpc-access - For information on how to configure Cloud Run with an existing - VPC Connector, visit - https://cloud.google.com/run/docs/configuring/connecting-vpc - - Attributes: - connector (str): - VPC Access connector name. - Format: - projects/{project}/locations/{location}/connectors/{connector} - egress (google.cloud.run_v2.types.VpcAccess.VpcEgress): - Traffic VPC egress settings. - """ - class VpcEgress(proto.Enum): - r"""Egress options for VPC access.""" - VPC_EGRESS_UNSPECIFIED = 0 - ALL_TRAFFIC = 1 - PRIVATE_RANGES_ONLY = 2 - - connector = proto.Field( - proto.STRING, - number=1, - ) - egress = proto.Field( - proto.ENUM, - number=2, - enum=VpcEgress, - ) - - -class BinaryAuthorization(proto.Message): - r"""Settings for Binary Authorization feature. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - use_default (bool): - If True, indicates to use the default - project's binary authorization policy. If False, - binary authorization will be disabled. - - This field is a member of `oneof`_ ``binauthz_method``. - breakglass_justification (str): - If present, indicates to use Breakglass using this - justification. If use_default is False, then it must be - empty. For more information on breakglass, see - https://cloud.google.com/binary-authorization/docs/using-breakglass - """ - - use_default = proto.Field( - proto.BOOL, - number=1, - oneof='binauthz_method', - ) - breakglass_justification = proto.Field( - proto.STRING, - number=2, - ) - - -class RevisionScaling(proto.Message): - r"""Settings for revision-level scaling settings. - - Attributes: - min_instance_count (int): - Minimum number of serving instances that this - resource should have. - max_instance_count (int): - Maximum number of serving instances that this - resource should have. - """ - - min_instance_count = proto.Field( - proto.INT32, - number=1, - ) - max_instance_count = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py deleted file mode 100644 index d2f4263..0000000 --- a/owl-bot-staging/v2/noxfile.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", -] - -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") - -BLACK_VERSION = "black==19.10b0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.9" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -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/run_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-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=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_async.py deleted file mode 100644 index 27d3195..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteRevision -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Revisions_DeleteRevision_async] -from google.cloud import run_v2 - - -async def sample_delete_revision(): - # Create a client - client = run_v2.RevisionsAsyncClient() - - # Initialize request argument(s) - request = run_v2.DeleteRevisionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_revision(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END run_v2_generated_Revisions_DeleteRevision_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync.py deleted file mode 100644 index c5196ac..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteRevision -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Revisions_DeleteRevision_sync] -from google.cloud import run_v2 - - -def sample_delete_revision(): - # Create a client - client = run_v2.RevisionsClient() - - # Initialize request argument(s) - request = run_v2.DeleteRevisionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_revision(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END run_v2_generated_Revisions_DeleteRevision_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_async.py deleted file mode 100644 index c4c2433..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetRevision -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Revisions_GetRevision_async] -from google.cloud import run_v2 - - -async def sample_get_revision(): - # Create a client - client = run_v2.RevisionsAsyncClient() - - # Initialize request argument(s) - request = run_v2.GetRevisionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_revision(request=request) - - # Handle the response - print(response) - -# [END run_v2_generated_Revisions_GetRevision_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_sync.py deleted file mode 100644 index 81c70c9..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_get_revision_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetRevision -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Revisions_GetRevision_sync] -from google.cloud import run_v2 - - -def sample_get_revision(): - # Create a client - client = run_v2.RevisionsClient() - - # Initialize request argument(s) - request = run_v2.GetRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.get_revision(request=request) - - # Handle the response - print(response) - -# [END run_v2_generated_Revisions_GetRevision_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_async.py deleted file mode 100644 index b59fa1f..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListRevisions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Revisions_ListRevisions_async] -from google.cloud import run_v2 - - -async def sample_list_revisions(): - # Create a client - client = run_v2.RevisionsAsyncClient() - - # Initialize request argument(s) - request = run_v2.ListRevisionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_revisions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END run_v2_generated_Revisions_ListRevisions_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync.py deleted file mode 100644 index e76f3f3..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListRevisions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Revisions_ListRevisions_sync] -from google.cloud import run_v2 - - -def sample_list_revisions(): - # Create a client - client = run_v2.RevisionsClient() - - # Initialize request argument(s) - request = run_v2.ListRevisionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END run_v2_generated_Revisions_ListRevisions_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_async.py deleted file mode 100644 index 9d067f2..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_CreateService_async] -from google.cloud import run_v2 - - -async def sample_create_service(): - # Create a client - client = run_v2.ServicesAsyncClient() - - # Initialize request argument(s) - request = run_v2.CreateServiceRequest( - parent="parent_value", - service_id="service_id_value", - ) - - # Make the request - operation = client.create_service(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END run_v2_generated_Services_CreateService_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_sync.py deleted file mode 100644 index 88a1cf3..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_create_service_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_CreateService_sync] -from google.cloud import run_v2 - - -def sample_create_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.CreateServiceRequest( - parent="parent_value", - service_id="service_id_value", - ) - - # Make the request - operation = client.create_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END run_v2_generated_Services_CreateService_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_async.py deleted file mode 100644 index 6ae4a76..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_async.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_DeleteService_async] -from google.cloud import run_v2 - - -async def sample_delete_service(): - # Create a client - client = run_v2.ServicesAsyncClient() - - # Initialize request argument(s) - request = run_v2.DeleteServiceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_service(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END run_v2_generated_Services_DeleteService_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_sync.py deleted file mode 100644 index 6cde79a..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_delete_service_sync.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_DeleteService_sync] -from google.cloud import run_v2 - - -def sample_delete_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.DeleteServiceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END run_v2_generated_Services_DeleteService_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_async.py deleted file mode 100644 index a492b45..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_GetIamPolicy_async] -from google.cloud import run_v2 - - -async def sample_get_iam_policy(): - # Create a client - client = run_v2.ServicesAsyncClient() - - # Initialize request argument(s) - request = run_v2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END run_v2_generated_Services_GetIamPolicy_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync.py deleted file mode 100644 index b30e6fb..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_GetIamPolicy_sync] -from google.cloud import run_v2 - - -def sample_get_iam_policy(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END run_v2_generated_Services_GetIamPolicy_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_async.py deleted file mode 100644 index 4b4a653..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_GetService_async] -from google.cloud import run_v2 - - -async def sample_get_service(): - # Create a client - client = run_v2.ServicesAsyncClient() - - # Initialize request argument(s) - request = run_v2.GetServiceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_service(request=request) - - # Handle the response - print(response) - -# [END run_v2_generated_Services_GetService_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_sync.py deleted file mode 100644 index b04592b..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_get_service_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_GetService_sync] -from google.cloud import run_v2 - - -def sample_get_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.GetServiceRequest( - name="name_value", - ) - - # Make the request - response = client.get_service(request=request) - - # Handle the response - print(response) - -# [END run_v2_generated_Services_GetService_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_async.py deleted file mode 100644 index bd2a32c..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServices -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_ListServices_async] -from google.cloud import run_v2 - - -async def sample_list_services(): - # Create a client - client = run_v2.ServicesAsyncClient() - - # Initialize request argument(s) - request = run_v2.ListServicesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_services(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END run_v2_generated_Services_ListServices_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_sync.py deleted file mode 100644 index fc68512..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_list_services_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServices -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_ListServices_sync] -from google.cloud import run_v2 - - -def sample_list_services(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.ListServicesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_services(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END run_v2_generated_Services_ListServices_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_async.py deleted file mode 100644 index a39cadd..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_async.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_SetIamPolicy_async] -from google.cloud import run_v2 - - -async def sample_set_iam_policy(): - # Create a client - client = run_v2.ServicesAsyncClient() - - # Initialize request argument(s) - request = run_v2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END run_v2_generated_Services_SetIamPolicy_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync.py deleted file mode 100644 index fac34da..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_SetIamPolicy_sync] -from google.cloud import run_v2 - - -def sample_set_iam_policy(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END run_v2_generated_Services_SetIamPolicy_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_async.py deleted file mode 100644 index 74ee78f..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_async.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_TestIamPermissions_async] -from google.cloud import run_v2 - - -async def sample_test_iam_permissions(): - # Create a client - client = run_v2.ServicesAsyncClient() - - # Initialize request argument(s) - request = run_v2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value_1', 'permissions_value_2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END run_v2_generated_Services_TestIamPermissions_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync.py deleted file mode 100644 index a33107a..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_TestIamPermissions_sync] -from google.cloud import run_v2 - - -def sample_test_iam_permissions(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value_1', 'permissions_value_2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END run_v2_generated_Services_TestIamPermissions_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_async.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_async.py deleted file mode 100644 index 41d52f4..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_async.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_UpdateService_async] -from google.cloud import run_v2 - - -async def sample_update_service(): - # Create a client - client = run_v2.ServicesAsyncClient() - - # Initialize request argument(s) - request = run_v2.UpdateServiceRequest( - ) - - # Make the request - operation = client.update_service(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END run_v2_generated_Services_UpdateService_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_sync.py b/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_sync.py deleted file mode 100644 index ccce2fc..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/run_v2_generated_services_update_service_sync.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-run - - -# [START run_v2_generated_Services_UpdateService_sync] -from google.cloud import run_v2 - - -def sample_update_service(): - # Create a client - client = run_v2.ServicesClient() - - # Initialize request argument(s) - request = run_v2.UpdateServiceRequest( - ) - - # Make the request - operation = client.update_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END run_v2_generated_Services_UpdateService_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_run_v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_run_v2.json deleted file mode 100644 index 240cdb5..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_run_v2.json +++ /dev/null @@ -1,983 +0,0 @@ -{ - "snippets": [ - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Revisions" - }, - "shortName": "DeleteRevision" - } - }, - "file": "run_v2_generated_revisions_delete_revision_async.py", - "regionTag": "run_v2_generated_Revisions_DeleteRevision_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Revisions" - }, - "shortName": "DeleteRevision" - } - }, - "file": "run_v2_generated_revisions_delete_revision_sync.py", - "regionTag": "run_v2_generated_Revisions_DeleteRevision_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Revisions" - }, - "shortName": "GetRevision" - } - }, - "file": "run_v2_generated_revisions_get_revision_async.py", - "regionTag": "run_v2_generated_Revisions_GetRevision_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Revisions" - }, - "shortName": "GetRevision" - } - }, - "file": "run_v2_generated_revisions_get_revision_sync.py", - "regionTag": "run_v2_generated_Revisions_GetRevision_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Revisions" - }, - "shortName": "ListRevisions" - } - }, - "file": "run_v2_generated_revisions_list_revisions_async.py", - "regionTag": "run_v2_generated_Revisions_ListRevisions_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Revisions" - }, - "shortName": "ListRevisions" - } - }, - "file": "run_v2_generated_revisions_list_revisions_sync.py", - "regionTag": "run_v2_generated_Revisions_ListRevisions_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "CreateService" - } - }, - "file": "run_v2_generated_services_create_service_async.py", - "regionTag": "run_v2_generated_Services_CreateService_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "CreateService" - } - }, - "file": "run_v2_generated_services_create_service_sync.py", - "regionTag": "run_v2_generated_Services_CreateService_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 46, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "start": 47, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "DeleteService" - } - }, - "file": "run_v2_generated_services_delete_service_async.py", - "regionTag": "run_v2_generated_Services_DeleteService_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "DeleteService" - } - }, - "file": "run_v2_generated_services_delete_service_sync.py", - "regionTag": "run_v2_generated_Services_DeleteService_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 45, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "start": 46, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "GetIamPolicy" - } - }, - "file": "run_v2_generated_services_get_iam_policy_async.py", - "regionTag": "run_v2_generated_Services_GetIamPolicy_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "GetIamPolicy" - } - }, - "file": "run_v2_generated_services_get_iam_policy_sync.py", - "regionTag": "run_v2_generated_Services_GetIamPolicy_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "GetService" - } - }, - "file": "run_v2_generated_services_get_service_async.py", - "regionTag": "run_v2_generated_Services_GetService_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "GetService" - } - }, - "file": "run_v2_generated_services_get_service_sync.py", - "regionTag": "run_v2_generated_Services_GetService_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "ListServices" - } - }, - "file": "run_v2_generated_services_list_services_async.py", - "regionTag": "run_v2_generated_Services_ListServices_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "ListServices" - } - }, - "file": "run_v2_generated_services_list_services_sync.py", - "regionTag": "run_v2_generated_Services_ListServices_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "SetIamPolicy" - } - }, - "file": "run_v2_generated_services_set_iam_policy_async.py", - "regionTag": "run_v2_generated_Services_SetIamPolicy_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "SetIamPolicy" - } - }, - "file": "run_v2_generated_services_set_iam_policy_sync.py", - "regionTag": "run_v2_generated_Services_SetIamPolicy_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 38, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 41, - "start": 39, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 42, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "TestIamPermissions" - } - }, - "file": "run_v2_generated_services_test_iam_permissions_async.py", - "regionTag": "run_v2_generated_Services_TestIamPermissions_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "TestIamPermissions" - } - }, - "file": "run_v2_generated_services_test_iam_permissions_sync.py", - "regionTag": "run_v2_generated_Services_TestIamPermissions_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "async": true, - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "UpdateService" - } - }, - "file": "run_v2_generated_services_update_service_async.py", - "regionTag": "run_v2_generated_Services_UpdateService_async", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ] - }, - { - "clientMethod": { - "method": { - "service": { - "shortName": "Services" - }, - "shortName": "UpdateService" - } - }, - "file": "run_v2_generated_services_update_service_sync.py", - "regionTag": "run_v2_generated_Services_UpdateService_sync", - "segments": [ - { - "end": 47, - "start": 27, - "type": "FULL" - }, - { - "end": 47, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 44, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 48, - "start": 45, - "type": "RESPONSE_HANDLING" - } - ] - } - ] -} diff --git a/owl-bot-staging/v2/scripts/fixup_run_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_run_v2_keywords.py deleted file mode 100644 index aef6ae6..0000000 --- a/owl-bot-staging/v2/scripts/fixup_run_v2_keywords.py +++ /dev/null @@ -1,186 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 runCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_service': ('parent', 'service', 'service_id', 'validate_only', ), - 'delete_revision': ('name', 'validate_only', 'etag', ), - 'delete_service': ('name', 'validate_only', 'etag', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_revision': ('name', ), - 'get_service': ('name', ), - 'list_revisions': ('parent', 'page_size', 'page_token', 'show_deleted', ), - 'list_services': ('parent', 'page_size', 'page_token', 'show_deleted', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_service': ('service', 'update_mask', 'validate_only', 'allow_missing', ), - } - - 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=runCallTransformer(), -): - """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 run 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/v2/setup.py b/owl-bot-staging/v2/setup.py deleted file mode 100644 index 8393a95..0000000 --- a/owl-bot-staging/v2/setup.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-run', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-run", - 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.31.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'googleapis-common-protos >= 1.55.0, <2.0.0dev', - 'proto-plus >= 1.19.7', - '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', - 'Programming Language :: Python :: 3.10', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v2/tests/unit/gapic/run_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/run_v2/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v2/tests/unit/gapic/run_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v2/tests/unit/gapic/run_v2/test_revisions.py b/owl-bot-staging/v2/tests/unit/gapic/run_v2/test_revisions.py deleted file mode 100644 index 9a39f9c..0000000 --- a/owl-bot-staging/v2/tests/unit/gapic/run_v2/test_revisions.py +++ /dev/null @@ -1,2197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.run_v2.services.revisions import RevisionsAsyncClient -from google.cloud.run_v2.services.revisions import RevisionsClient -from google.cloud.run_v2.services.revisions import pagers -from google.cloud.run_v2.services.revisions import transports -from google.cloud.run_v2.types import condition -from google.cloud.run_v2.types import k8s_min -from google.cloud.run_v2.types import revision -from google.cloud.run_v2.types import vendor_settings -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert RevisionsClient._get_default_mtls_endpoint(None) is None - assert RevisionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RevisionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RevisionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RevisionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RevisionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RevisionsClient, "grpc"), - (RevisionsAsyncClient, "grpc_asyncio"), -]) -def test_revisions_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'run.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RevisionsGrpcTransport, "grpc"), - (transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_revisions_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RevisionsClient, "grpc"), - (RevisionsAsyncClient, "grpc_asyncio"), -]) -def test_revisions_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'run.googleapis.com:443' - ) - - -def test_revisions_client_get_transport_class(): - transport = RevisionsClient.get_transport_class() - available_transports = [ - transports.RevisionsGrpcTransport, - ] - assert transport in available_transports - - transport = RevisionsClient.get_transport_class("grpc") - assert transport == transports.RevisionsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RevisionsClient, transports.RevisionsGrpcTransport, "grpc"), - (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(RevisionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsClient)) -@mock.patch.object(RevisionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsAsyncClient)) -def test_revisions_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(RevisionsClient, '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(RevisionsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RevisionsClient, transports.RevisionsGrpcTransport, "grpc", "true"), - (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RevisionsClient, transports.RevisionsGrpcTransport, "grpc", "false"), - (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(RevisionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsClient)) -@mock.patch.object(RevisionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_revisions_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - RevisionsClient, RevisionsAsyncClient -]) -@mock.patch.object(RevisionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsClient)) -@mock.patch.object(RevisionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RevisionsAsyncClient)) -def test_revisions_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RevisionsClient, transports.RevisionsGrpcTransport, "grpc"), - (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_revisions_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RevisionsClient, transports.RevisionsGrpcTransport, "grpc", grpc_helpers), - (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_revisions_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_revisions_client_client_options_from_dict(): - with mock.patch('google.cloud.run_v2.services.revisions.transports.RevisionsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RevisionsClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RevisionsClient, transports.RevisionsGrpcTransport, "grpc", grpc_helpers), - (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_revisions_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "run.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="run.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - revision.GetRevisionRequest, - dict, -]) -def test_get_revision(request_type, transport: str = 'grpc'): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = revision.Revision( - name='name_value', - uid='uid_value', - generation=1068, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - service='service_value', - container_concurrency=2253, - service_account='service_account_value', - confidential=True, - execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_DEFAULT, - encryption_key='encryption_key_value', - reconciling=True, - observed_generation=2021, - log_uri='log_uri_value', - etag='etag_value', - ) - response = client.get_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == revision.GetRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, revision.Revision) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.generation == 1068 - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.service == 'service_value' - assert response.container_concurrency == 2253 - assert response.service_account == 'service_account_value' - assert response.confidential is True - assert response.execution_environment == vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_DEFAULT - assert response.encryption_key == 'encryption_key_value' - assert response.reconciling is True - assert response.observed_generation == 2021 - assert response.log_uri == 'log_uri_value' - assert response.etag == 'etag_value' - - -def test_get_revision_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - client.get_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == revision.GetRevisionRequest() - -@pytest.mark.asyncio -async def test_get_revision_async(transport: str = 'grpc_asyncio', request_type=revision.GetRevisionRequest): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(revision.Revision( - name='name_value', - uid='uid_value', - generation=1068, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - service='service_value', - container_concurrency=2253, - service_account='service_account_value', - confidential=True, - execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_DEFAULT, - encryption_key='encryption_key_value', - reconciling=True, - observed_generation=2021, - log_uri='log_uri_value', - etag='etag_value', - )) - response = await client.get_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == revision.GetRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, revision.Revision) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.generation == 1068 - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.service == 'service_value' - assert response.container_concurrency == 2253 - assert response.service_account == 'service_account_value' - assert response.confidential is True - assert response.execution_environment == vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_DEFAULT - assert response.encryption_key == 'encryption_key_value' - assert response.reconciling is True - assert response.observed_generation == 2021 - assert response.log_uri == 'log_uri_value' - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_revision_async_from_dict(): - await test_get_revision_async(request_type=dict) - - -def test_get_revision_field_headers(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = revision.GetRevisionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - call.return_value = revision.Revision() - client.get_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_revision_field_headers_async(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = revision.GetRevisionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(revision.Revision()) - await client.get_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_revision_flattened(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = revision.Revision() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_revision( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_revision_flattened_error(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_revision( - revision.GetRevisionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_revision_flattened_async(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = revision.Revision() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(revision.Revision()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_revision( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_revision_flattened_error_async(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_revision( - revision.GetRevisionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - revision.ListRevisionsRequest, - dict, -]) -def test_list_revisions(request_type, transport: str = 'grpc'): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = revision.ListRevisionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == revision.ListRevisionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRevisionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_revisions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - client.list_revisions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == revision.ListRevisionsRequest() - -@pytest.mark.asyncio -async def test_list_revisions_async(transport: str = 'grpc_asyncio', request_type=revision.ListRevisionsRequest): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(revision.ListRevisionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == revision.ListRevisionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRevisionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_revisions_async_from_dict(): - await test_list_revisions_async(request_type=dict) - - -def test_list_revisions_field_headers(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = revision.ListRevisionsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - call.return_value = revision.ListRevisionsResponse() - client.list_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_revisions_field_headers_async(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = revision.ListRevisionsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(revision.ListRevisionsResponse()) - await client.list_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_revisions_flattened(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = revision.ListRevisionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_revisions( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_revisions_flattened_error(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_revisions( - revision.ListRevisionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_revisions_flattened_async(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = revision.ListRevisionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(revision.ListRevisionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_revisions( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_revisions_flattened_error_async(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_revisions( - revision.ListRevisionsRequest(), - parent='parent_value', - ) - - -def test_list_revisions_pager(transport_name: str = "grpc"): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - revision.Revision(), - revision.Revision(), - ], - next_page_token='abc', - ), - revision.ListRevisionsResponse( - revisions=[], - next_page_token='def', - ), - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - ], - next_page_token='ghi', - ), - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - revision.Revision(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_revisions(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, revision.Revision) - for i in results) -def test_list_revisions_pages(transport_name: str = "grpc"): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - revision.Revision(), - revision.Revision(), - ], - next_page_token='abc', - ), - revision.ListRevisionsResponse( - revisions=[], - next_page_token='def', - ), - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - ], - next_page_token='ghi', - ), - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - revision.Revision(), - ], - ), - RuntimeError, - ) - pages = list(client.list_revisions(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_revisions_async_pager(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - revision.Revision(), - revision.Revision(), - ], - next_page_token='abc', - ), - revision.ListRevisionsResponse( - revisions=[], - next_page_token='def', - ), - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - ], - next_page_token='ghi', - ), - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - revision.Revision(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_revisions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, revision.Revision) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_revisions_async_pages(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - revision.Revision(), - revision.Revision(), - ], - next_page_token='abc', - ), - revision.ListRevisionsResponse( - revisions=[], - next_page_token='def', - ), - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - ], - next_page_token='ghi', - ), - revision.ListRevisionsResponse( - revisions=[ - revision.Revision(), - revision.Revision(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_revisions(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - revision.DeleteRevisionRequest, - dict, -]) -def test_delete_revision(request_type, transport: str = 'grpc'): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == revision.DeleteRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_revision_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RevisionsClient( - 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_revision), - '__call__') as call: - client.delete_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == revision.DeleteRevisionRequest() - -@pytest.mark.asyncio -async def test_delete_revision_async(transport: str = 'grpc_asyncio', request_type=revision.DeleteRevisionRequest): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == revision.DeleteRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_revision_async_from_dict(): - await test_delete_revision_async(request_type=dict) - - -def test_delete_revision_field_headers(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = revision.DeleteRevisionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_revision), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_revision_field_headers_async(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = revision.DeleteRevisionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_revision), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_revision_flattened(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_revision( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_revision_flattened_error(): - client = RevisionsClient( - 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_revision( - revision.DeleteRevisionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_revision_flattened_async(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_revision( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_revision_flattened_error_async(): - client = RevisionsAsyncClient( - 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_revision( - revision.DeleteRevisionRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RevisionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RevisionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RevisionsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RevisionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RevisionsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RevisionsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RevisionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RevisionsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RevisionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RevisionsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RevisionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RevisionsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RevisionsGrpcTransport, - transports.RevisionsGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", -]) -def test_transport_kind(transport_name): - transport = RevisionsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RevisionsGrpcTransport, - ) - -def test_revisions_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RevisionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_revisions_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.run_v2.services.revisions.transports.RevisionsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RevisionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_revision', - 'list_revisions', - 'delete_revision', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_revisions_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.run_v2.services.revisions.transports.RevisionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RevisionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_revisions_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.run_v2.services.revisions.transports.RevisionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RevisionsTransport() - adc.assert_called_once() - - -def test_revisions_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) - RevisionsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RevisionsGrpcTransport, - transports.RevisionsGrpcAsyncIOTransport, - ], -) -def test_revisions_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,grpc_helpers", - [ - (transports.RevisionsGrpcTransport, grpc_helpers), - (transports.RevisionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_revisions_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( - "run.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="run.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RevisionsGrpcTransport, transports.RevisionsGrpcAsyncIOTransport]) -def test_revisions_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_revisions_host_no_port(transport_name): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='run.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'run.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_revisions_host_with_port(transport_name): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='run.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'run.googleapis.com:8000' - ) - -def test_revisions_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RevisionsGrpcTransport( - 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_revisions_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RevisionsGrpcAsyncIOTransport( - 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.RevisionsGrpcTransport, transports.RevisionsGrpcAsyncIOTransport]) -def test_revisions_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.RevisionsGrpcTransport, transports.RevisionsGrpcAsyncIOTransport]) -def test_revisions_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_revisions_grpc_lro_client(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_revisions_grpc_lro_async_client(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_connector_path(): - project = "squid" - location = "clam" - connector = "whelk" - expected = "projects/{project}/locations/{location}/connectors/{connector}".format(project=project, location=location, connector=connector, ) - actual = RevisionsClient.connector_path(project, location, connector) - assert expected == actual - - -def test_parse_connector_path(): - expected = { - "project": "octopus", - "location": "oyster", - "connector": "nudibranch", - } - path = RevisionsClient.connector_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_connector_path(path) - assert expected == actual - -def test_crypto_key_path(): - project = "cuttlefish" - location = "mussel" - key_ring = "winkle" - crypto_key = "nautilus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - actual = RevisionsClient.crypto_key_path(project, location, key_ring, crypto_key) - assert expected == actual - - -def test_parse_crypto_key_path(): - expected = { - "project": "scallop", - "location": "abalone", - "key_ring": "squid", - "crypto_key": "clam", - } - path = RevisionsClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_crypto_key_path(path) - assert expected == actual - -def test_revision_path(): - project = "whelk" - location = "octopus" - service = "oyster" - revision = "nudibranch" - expected = "projects/{project}/locations/{location}/services/{service}/revisions/{revision}".format(project=project, location=location, service=service, revision=revision, ) - actual = RevisionsClient.revision_path(project, location, service, revision) - assert expected == actual - - -def test_parse_revision_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "service": "winkle", - "revision": "nautilus", - } - path = RevisionsClient.revision_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_revision_path(path) - assert expected == actual - -def test_secret_path(): - project = "scallop" - secret = "abalone" - expected = "projects/{project}/secrets/{secret}".format(project=project, secret=secret, ) - actual = RevisionsClient.secret_path(project, secret) - assert expected == actual - - -def test_parse_secret_path(): - expected = { - "project": "squid", - "secret": "clam", - } - path = RevisionsClient.secret_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_secret_path(path) - assert expected == actual - -def test_secret_version_path(): - project = "whelk" - secret = "octopus" - version = "oyster" - expected = "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) - actual = RevisionsClient.secret_version_path(project, secret, version) - assert expected == actual - - -def test_parse_secret_version_path(): - expected = { - "project": "nudibranch", - "secret": "cuttlefish", - "version": "mussel", - } - path = RevisionsClient.secret_version_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_secret_version_path(path) - assert expected == actual - -def test_service_path(): - project = "winkle" - location = "nautilus" - service = "scallop" - expected = "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) - actual = RevisionsClient.service_path(project, location, service) - assert expected == actual - - -def test_parse_service_path(): - expected = { - "project": "abalone", - "location": "squid", - "service": "clam", - } - path = RevisionsClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_service_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RevisionsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = RevisionsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = RevisionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = RevisionsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RevisionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = RevisionsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = RevisionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = RevisionsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RevisionsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = RevisionsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.RevisionsTransport, '_prep_wrapped_messages') as prep: - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RevisionsTransport, '_prep_wrapped_messages') as prep: - transport_class = RevisionsClient.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 = RevisionsAsyncClient( - 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 = RevisionsClient( - 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 = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (RevisionsClient, transports.RevisionsGrpcTransport), - (RevisionsAsyncClient, transports.RevisionsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/run_v2/test_services.py b/owl-bot-staging/v2/tests/unit/gapic/run_v2/test_services.py deleted file mode 100644 index e4ae1cc..0000000 --- a/owl-bot-staging/v2/tests/unit/gapic/run_v2/test_services.py +++ /dev/null @@ -1,3218 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import launch_stage_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.run_v2.services.services import ServicesAsyncClient -from google.cloud.run_v2.services.services import ServicesClient -from google.cloud.run_v2.services.services import pagers -from google.cloud.run_v2.services.services import transports -from google.cloud.run_v2.types import condition -from google.cloud.run_v2.types import k8s_min -from google.cloud.run_v2.types import revision_template -from google.cloud.run_v2.types import service -from google.cloud.run_v2.types import service as gcr_service -from google.cloud.run_v2.types import traffic_target -from google.cloud.run_v2.types import vendor_settings -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -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 - - -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 ServicesClient._get_default_mtls_endpoint(None) is None - assert ServicesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServicesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServicesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServicesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServicesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServicesClient, "grpc"), - (ServicesAsyncClient, "grpc_asyncio"), -]) -def test_services_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'run.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServicesGrpcTransport, "grpc"), - (transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_services_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServicesClient, "grpc"), - (ServicesAsyncClient, "grpc_asyncio"), -]) -def test_services_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'run.googleapis.com:443' - ) - - -def test_services_client_get_transport_class(): - transport = ServicesClient.get_transport_class() - available_transports = [ - transports.ServicesGrpcTransport, - ] - assert transport in available_transports - - transport = ServicesClient.get_transport_class("grpc") - assert transport == transports.ServicesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServicesClient, transports.ServicesGrpcTransport, "grpc"), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)) -@mock.patch.object(ServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesAsyncClient)) -def test_services_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(ServicesClient, '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(ServicesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServicesClient, transports.ServicesGrpcTransport, "grpc", "true"), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServicesClient, transports.ServicesGrpcTransport, "grpc", "false"), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)) -@mock.patch.object(ServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_services_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class", [ - ServicesClient, ServicesAsyncClient -]) -@mock.patch.object(ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)) -@mock.patch.object(ServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesAsyncClient)) -def test_services_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServicesClient, transports.ServicesGrpcTransport, "grpc"), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_services_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServicesClient, transports.ServicesGrpcTransport, "grpc", grpc_helpers), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_services_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_services_client_client_options_from_dict(): - with mock.patch('google.cloud.run_v2.services.services.transports.ServicesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServicesClient( - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServicesClient, transports.ServicesGrpcTransport, "grpc", grpc_helpers), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_services_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "run.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="run.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - gcr_service.CreateServiceRequest, - dict, -]) -def test_create_service(request_type, transport: str = 'grpc'): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcr_service.CreateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -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 = ServicesClient( - 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] == gcr_service.CreateServiceRequest() - -@pytest.mark.asyncio -async def test_create_service_async(transport: str = 'grpc_asyncio', request_type=gcr_service.CreateServiceRequest): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcr_service.CreateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_service_async_from_dict(): - await test_create_service_async(request_type=dict) - - -def test_create_service_field_headers(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcr_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 = operations_pb2.Operation(name='operations/op') - 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 = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcr_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(operations_pb2.Operation(name='operations/op')) - 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 = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_service( - parent='parent_value', - service=gcr_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].service - mock_val = gcr_service.Service(name='name_value') - assert arg == mock_val - arg = args[0].service_id - mock_val = 'service_id_value' - assert arg == mock_val - - -def test_create_service_flattened_error(): - client = ServicesClient( - 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( - gcr_service.CreateServiceRequest(), - parent='parent_value', - service=gcr_service.Service(name='name_value'), - service_id='service_id_value', - ) - -@pytest.mark.asyncio -async def test_create_service_flattened_async(): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_service( - parent='parent_value', - service=gcr_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].service - mock_val = gcr_service.Service(name='name_value') - assert arg == mock_val - arg = args[0].service_id - mock_val = 'service_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_service_flattened_error_async(): - client = ServicesAsyncClient( - 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( - gcr_service.CreateServiceRequest(), - parent='parent_value', - service=gcr_service.Service(name='name_value'), - service_id='service_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.GetServiceRequest, - dict, -]) -def test_get_service(request_type, transport: str = 'grpc'): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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', - description='description_value', - uid='uid_value', - generation=1068, - creator='creator_value', - last_modifier='last_modifier_value', - client='client_value', - client_version='client_version_value', - ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - observed_generation=2021, - latest_ready_revision='latest_ready_revision_value', - latest_created_revision='latest_created_revision_value', - uri='uri_value', - reconciling=True, - etag='etag_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] == service.GetServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.uid == 'uid_value' - assert response.generation == 1068 - assert response.creator == 'creator_value' - assert response.last_modifier == 'last_modifier_value' - assert response.client == 'client_value' - assert response.client_version == 'client_version_value' - assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.observed_generation == 2021 - assert response.latest_ready_revision == 'latest_ready_revision_value' - assert response.latest_created_revision == 'latest_created_revision_value' - assert response.uri == 'uri_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - - -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 = ServicesClient( - 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] == service.GetServiceRequest() - -@pytest.mark.asyncio -async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=service.GetServiceRequest): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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', - description='description_value', - uid='uid_value', - generation=1068, - creator='creator_value', - last_modifier='last_modifier_value', - client='client_value', - client_version='client_version_value', - ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - observed_generation=2021, - latest_ready_revision='latest_ready_revision_value', - latest_created_revision='latest_created_revision_value', - uri='uri_value', - reconciling=True, - etag='etag_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] == service.GetServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.uid == 'uid_value' - assert response.generation == 1068 - assert response.creator == 'creator_value' - assert response.last_modifier == 'last_modifier_value' - assert response.client == 'client_value' - assert response.client_version == 'client_version_value' - assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.observed_generation == 2021 - assert response.latest_ready_revision == 'latest_ready_revision_value' - assert response.latest_created_revision == 'latest_created_revision_value' - assert response.uri == 'uri_value' - assert response.reconciling is True - assert response.etag == 'etag_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 = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.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 = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.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 = ServicesClient( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_service_flattened_error(): - client = ServicesClient( - 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( - service.GetServiceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_service_flattened_async(): - client = ServicesAsyncClient( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_service_flattened_error_async(): - client = ServicesAsyncClient( - 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( - service.GetServiceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.ListServicesRequest, - dict, -]) -def test_list_services(request_type, transport: str = 'grpc'): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = 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] == 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_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 = ServicesClient( - 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] == service.ListServicesRequest() - -@pytest.mark.asyncio -async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=service.ListServicesRequest): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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(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] == 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 = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.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 = 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 = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.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(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 = ServicesClient( - 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 = 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_services_flattened_error(): - client = ServicesClient( - 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( - service.ListServicesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_services_flattened_async(): - client = ServicesAsyncClient( - 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 = service.ListServicesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_services_flattened_error_async(): - client = ServicesAsyncClient( - 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( - service.ListServicesRequest(), - parent='parent_value', - ) - - -def test_list_services_pager(transport_name: str = "grpc"): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - service.ListServicesResponse( - services=[], - next_page_token='def', - ), - service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - 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(transport_name: str = "grpc"): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - service.ListServicesResponse( - services=[], - next_page_token='def', - ), - service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - 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 = ServicesAsyncClient( - 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 = ( - service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - service.ListServicesResponse( - services=[], - next_page_token='def', - ), - service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - 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: # pragma: no branch - 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 = ServicesAsyncClient( - 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 = ( - service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - service.ListServicesResponse( - services=[], - next_page_token='def', - ), - service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_services(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - gcr_service.UpdateServiceRequest, - dict, -]) -def test_update_service(request_type, transport: str = 'grpc'): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = operations_pb2.Operation(name='operations/spam') - 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] == gcr_service.UpdateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -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 = ServicesClient( - 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] == gcr_service.UpdateServiceRequest() - -@pytest.mark.asyncio -async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=gcr_service.UpdateServiceRequest): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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( - operations_pb2.Operation(name='operations/spam') - ) - 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] == gcr_service.UpdateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@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 = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcr_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 = operations_pb2.Operation(name='operations/op') - 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 = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcr_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(operations_pb2.Operation(name='operations/op')) - 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 = ServicesClient( - 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 = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_service( - service=gcr_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] - arg = args[0].service - mock_val = gcr_service.Service(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_service_flattened_error(): - client = ServicesClient( - 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( - gcr_service.UpdateServiceRequest(), - service=gcr_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 = ServicesAsyncClient( - 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 = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_service( - service=gcr_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] - arg = args[0].service - mock_val = gcr_service.Service(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_service_flattened_error_async(): - client = ServicesAsyncClient( - 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( - gcr_service.UpdateServiceRequest(), - service=gcr_service.Service(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - service.DeleteServiceRequest, - dict, -]) -def test_delete_service(request_type, transport: str = 'grpc'): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -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 = ServicesClient( - 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] == service.DeleteServiceRequest() - -@pytest.mark.asyncio -async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=service.DeleteServiceRequest): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_service_async_from_dict(): - await test_delete_service_async(request_type=dict) - - -def test_delete_service_field_headers(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.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 = operations_pb2.Operation(name='operations/op') - client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_service_field_headers_async(): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.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(operations_pb2.Operation(name='operations/op')) - await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_service_flattened(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_service( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_service_flattened_error(): - client = ServicesClient( - 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( - service.DeleteServiceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_service_flattened_async(): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_service( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_service_flattened_error_async(): - client = ServicesAsyncClient( - 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( - service.DeleteServiceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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 = ServicesClient( - 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 = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.get_iam_policy(request={ - 'resource': 'resource_value', - 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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 = ServicesClient( - 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 = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ServicesClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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 = ServicesClient( - 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 = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ServicesClient( - 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.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServicesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServicesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServicesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServicesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServicesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServicesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServicesGrpcTransport, - transports.ServicesGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", -]) -def test_transport_kind(transport_name): - transport = ServicesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServicesGrpcTransport, - ) - -def test_services_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServicesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_services_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.run_v2.services.services.transports.ServicesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServicesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_service', - 'get_service', - 'list_services', - 'update_service', - 'delete_service', - '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() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_services_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.run_v2.services.services.transports.ServicesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServicesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_services_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.run_v2.services.services.transports.ServicesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServicesTransport() - adc.assert_called_once() - - -def test_services_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) - ServicesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServicesGrpcTransport, - transports.ServicesGrpcAsyncIOTransport, - ], -) -def test_services_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,grpc_helpers", - [ - (transports.ServicesGrpcTransport, grpc_helpers), - (transports.ServicesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_services_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( - "run.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="run.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) -def test_services_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_services_host_no_port(transport_name): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='run.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'run.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_services_host_with_port(transport_name): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='run.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'run.googleapis.com:8000' - ) - -def test_services_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServicesGrpcTransport( - 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_services_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServicesGrpcAsyncIOTransport( - 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.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) -def test_services_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.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) -def test_services_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_services_grpc_lro_client(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_services_grpc_lro_async_client(): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_connector_path(): - project = "squid" - location = "clam" - connector = "whelk" - expected = "projects/{project}/locations/{location}/connectors/{connector}".format(project=project, location=location, connector=connector, ) - actual = ServicesClient.connector_path(project, location, connector) - assert expected == actual - - -def test_parse_connector_path(): - expected = { - "project": "octopus", - "location": "oyster", - "connector": "nudibranch", - } - path = ServicesClient.connector_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_connector_path(path) - assert expected == actual - -def test_crypto_key_path(): - project = "cuttlefish" - location = "mussel" - key_ring = "winkle" - crypto_key = "nautilus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - actual = ServicesClient.crypto_key_path(project, location, key_ring, crypto_key) - assert expected == actual - - -def test_parse_crypto_key_path(): - expected = { - "project": "scallop", - "location": "abalone", - "key_ring": "squid", - "crypto_key": "clam", - } - path = ServicesClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_crypto_key_path(path) - assert expected == actual - -def test_revision_path(): - project = "whelk" - location = "octopus" - service = "oyster" - revision = "nudibranch" - expected = "projects/{project}/locations/{location}/services/{service}/revisions/{revision}".format(project=project, location=location, service=service, revision=revision, ) - actual = ServicesClient.revision_path(project, location, service, revision) - assert expected == actual - - -def test_parse_revision_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "service": "winkle", - "revision": "nautilus", - } - path = ServicesClient.revision_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_revision_path(path) - assert expected == actual - -def test_secret_path(): - project = "scallop" - secret = "abalone" - expected = "projects/{project}/secrets/{secret}".format(project=project, secret=secret, ) - actual = ServicesClient.secret_path(project, secret) - assert expected == actual - - -def test_parse_secret_path(): - expected = { - "project": "squid", - "secret": "clam", - } - path = ServicesClient.secret_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_secret_path(path) - assert expected == actual - -def test_secret_version_path(): - project = "whelk" - secret = "octopus" - version = "oyster" - expected = "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) - actual = ServicesClient.secret_version_path(project, secret, version) - assert expected == actual - - -def test_parse_secret_version_path(): - expected = { - "project": "nudibranch", - "secret": "cuttlefish", - "version": "mussel", - } - path = ServicesClient.secret_version_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_secret_version_path(path) - assert expected == actual - -def test_service_path(): - project = "winkle" - location = "nautilus" - service = "scallop" - expected = "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) - actual = ServicesClient.service_path(project, location, service) - assert expected == actual - - -def test_parse_service_path(): - expected = { - "project": "abalone", - "location": "squid", - "service": "clam", - } - path = ServicesClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_service_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServicesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ServicesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServicesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ServicesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServicesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ServicesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ServicesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ServicesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ServicesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ServicesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ServicesTransport, '_prep_wrapped_messages') as prep: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServicesTransport, '_prep_wrapped_messages') as prep: - transport_class = ServicesClient.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 = ServicesAsyncClient( - 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 = ServicesClient( - 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 = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ServicesClient, transports.ServicesGrpcTransport), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/scripts/fixup_run_v2_keywords.py b/scripts/fixup_run_v2_keywords.py index 18d2094..aef6ae6 100644 --- a/scripts/fixup_run_v2_keywords.py +++ b/scripts/fixup_run_v2_keywords.py @@ -47,7 +47,7 @@ class runCallTransformer(cst.CSTTransformer): 'get_service': ('name', ), 'list_revisions': ('parent', 'page_size', 'page_token', 'show_deleted', ), 'list_services': ('parent', 'page_size', 'page_token', 'show_deleted', ), - 'set_iam_policy': ('resource', 'policy', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), 'test_iam_permissions': ('resource', 'permissions', ), 'update_service': ('service', 'update_mask', 'validate_only', 'allow_missing', ), } diff --git a/tests/unit/gapic/run_v2/test_revisions.py b/tests/unit/gapic/run_v2/test_revisions.py index a6a9c7c..7a67476 100644 --- a/tests/unit/gapic/run_v2/test_revisions.py +++ b/tests/unit/gapic/run_v2/test_revisions.py @@ -1652,6 +1652,19 @@ def test_transport_adc(transport_class): adc.assert_called_once() +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + ], +) +def test_transport_kind(transport_name): + transport = RevisionsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = RevisionsClient( @@ -1701,6 +1714,14 @@ def test_revisions_base_transport(): with pytest.raises(NotImplementedError): transport.operations_client + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + def test_revisions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file diff --git a/tests/unit/gapic/run_v2/test_services.py b/tests/unit/gapic/run_v2/test_services.py index 788855a..79098db 100644 --- a/tests/unit/gapic/run_v2/test_services.py +++ b/tests/unit/gapic/run_v2/test_services.py @@ -2378,6 +2378,7 @@ def test_set_iam_policy_from_dict_foreign(): request={ "resource": "resource_value", "policy": policy_pb2.Policy(version=774), + "update_mask": field_mask_pb2.FieldMask(paths=["paths_value"]), } ) call.assert_called() @@ -2654,6 +2655,19 @@ def test_transport_adc(transport_class): adc.assert_called_once() +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + ], +) +def test_transport_kind(transport_name): + transport = ServicesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ServicesClient( @@ -2708,6 +2722,14 @@ def test_services_base_transport(): with pytest.raises(NotImplementedError): transport.operations_client + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + def test_services_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file From 04b4e9cef407b72b994eeb19db68c0a13ffe7366 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 12 Apr 2022 00:01:33 +0000 Subject: [PATCH 3/3] fix(deps): require grpc-google-iam-v1 >=0.12.4 --- setup.py | 2 +- testing/constraints-3.6.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index dd11da3..0d667ac 100644 --- a/setup.py +++ b/setup.py @@ -32,7 +32,7 @@ "google-api-core[grpc] >= 1.31.5, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0", "proto-plus >= 1.15.0", "googleapis-common-protos >= 1.56.0", - "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", ] package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index c1b4ea6..a0c021a 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -7,4 +7,4 @@ google-api-core==1.31.5 proto-plus==1.15.0 googleapis-common-protos==1.56.0 -grpc-google-iam-v1==0.12.3 +grpc-google-iam-v1==0.12.4