From a5435176fe6cf9d66aaacbe3ceef564bbc298661 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 23 Jun 2022 22:40:05 +0000 Subject: [PATCH 01/16] feat: add audience parameter PiperOrigin-RevId: 456827138 Source-Link: https://github.com/googleapis/googleapis/commit/23f1a157189581734c7a77cddfeb7c5bc1e440ae Source-Link: https://github.com/googleapis/googleapis-gen/commit/4075a8514f676691ec156688a5bbf183aa9893ce Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNDA3NWE4NTE0ZjY3NjY5MWVjMTU2Njg4YTViYmYxODNhYTk4OTNjZSJ9 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/.flake8 | 33 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 ++ .../functions_v1/cloud_functions_service.rst | 10 + .../v1/docs/functions_v1/services.rst | 6 + .../v1/docs/functions_v1/types.rst | 7 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/google/cloud/functions/__init__.py | 67 + .../v1/google/cloud/functions/py.typed | 2 + .../v1/google/cloud/functions_v1/__init__.py | 68 + .../cloud/functions_v1/gapic_metadata.json | 133 + .../v1/google/cloud/functions_v1/py.typed | 2 + .../cloud/functions_v1/services/__init__.py | 15 + .../cloud_functions_service/__init__.py | 22 + .../cloud_functions_service/async_client.py | 1423 +++++++ .../cloud_functions_service/client.py | 1613 ++++++++ .../cloud_functions_service/pagers.py | 139 + .../transports/__init__.py | 33 + .../transports/base.py | 331 ++ .../transports/grpc.py | 593 +++ .../transports/grpc_asyncio.py | 592 +++ .../cloud/functions_v1/types/__init__.py | 66 + .../cloud/functions_v1/types/functions.py | 1067 +++++ .../cloud/functions_v1/types/operations.py | 108 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 180 + ...d_functions_service_call_function_async.py | 46 + ...ud_functions_service_call_function_sync.py | 46 + ...functions_service_create_function_async.py | 53 + ..._functions_service_create_function_sync.py | 53 + ...functions_service_delete_function_async.py | 49 + ..._functions_service_delete_function_sync.py | 49 + ...ons_service_generate_download_url_async.py | 44 + ...ions_service_generate_download_url_sync.py | 44 + ...tions_service_generate_upload_url_async.py | 44 + ...ctions_service_generate_upload_url_sync.py | 44 + ...ud_functions_service_get_function_async.py | 45 + ...oud_functions_service_get_function_sync.py | 45 + ..._functions_service_get_iam_policy_async.py | 46 + ...d_functions_service_get_iam_policy_sync.py | 46 + ..._functions_service_list_functions_async.py | 45 + ...d_functions_service_list_functions_sync.py | 45 + ..._functions_service_set_iam_policy_async.py | 46 + ...d_functions_service_set_iam_policy_sync.py | 46 + ...ions_service_test_iam_permissions_async.py | 47 + ...tions_service_test_iam_permissions_sync.py | 47 + ...functions_service_update_function_async.py | 52 + ..._functions_service_update_function_sync.py | 52 + .../snippet_metadata_functions_v1.json | 1753 ++++++++ .../v1/scripts/fixup_functions_v1_keywords.py | 186 + owl-bot-staging/v1/setup.py | 60 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/functions_v1/__init__.py | 16 + .../test_cloud_functions_service.py | 3682 +++++++++++++++++ 58 files changed, 13743 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/.flake8 create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst create mode 100644 owl-bot-staging/v1/docs/functions_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/functions_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/cloud/functions/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json create mode 100644 owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..ca93bdf --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/functions/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 0000000..9e8399a --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/functions *.py +recursive-include google/cloud/functions_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..533650a --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Functions 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 Functions API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..3464a12 --- /dev/null +++ b/owl-bot-staging/v1/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-functions 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-functions" +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-functions-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-functions.tex", + u"google-cloud-functions 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-functions", + u"Google Cloud Functions 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-functions", + u"google-cloud-functions Documentation", + author, + "google-cloud-functions", + "GAPIC library for Google Cloud Functions API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst b/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst new file mode 100644 index 0000000..36d0114 --- /dev/null +++ b/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst @@ -0,0 +1,10 @@ +CloudFunctionsService +--------------------------------------- + +.. automodule:: google.cloud.functions_v1.services.cloud_functions_service + :members: + :inherited-members: + +.. automodule:: google.cloud.functions_v1.services.cloud_functions_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/functions_v1/services.rst b/owl-bot-staging/v1/docs/functions_v1/services.rst new file mode 100644 index 0000000..89ae970 --- /dev/null +++ b/owl-bot-staging/v1/docs/functions_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Functions v1 API +========================================== +.. toctree:: + :maxdepth: 2 + + cloud_functions_service diff --git a/owl-bot-staging/v1/docs/functions_v1/types.rst b/owl-bot-staging/v1/docs/functions_v1/types.rst new file mode 100644 index 0000000..bebdfe9 --- /dev/null +++ b/owl-bot-staging/v1/docs/functions_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Functions v1 API +======================================= + +.. automodule:: google.cloud.functions_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..dc30f6d --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + functions_v1/services + functions_v1/types diff --git a/owl-bot-staging/v1/google/cloud/functions/__init__.py b/owl-bot-staging/v1/google/cloud/functions/__init__.py new file mode 100644 index 0000000..c34f3b0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions/__init__.py @@ -0,0 +1,67 @@ +# -*- 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.functions_v1.services.cloud_functions_service.client import CloudFunctionsServiceClient +from google.cloud.functions_v1.services.cloud_functions_service.async_client import CloudFunctionsServiceAsyncClient + +from google.cloud.functions_v1.types.functions import CallFunctionRequest +from google.cloud.functions_v1.types.functions import CallFunctionResponse +from google.cloud.functions_v1.types.functions import CloudFunction +from google.cloud.functions_v1.types.functions import CreateFunctionRequest +from google.cloud.functions_v1.types.functions import DeleteFunctionRequest +from google.cloud.functions_v1.types.functions import EventTrigger +from google.cloud.functions_v1.types.functions import FailurePolicy +from google.cloud.functions_v1.types.functions import GenerateDownloadUrlRequest +from google.cloud.functions_v1.types.functions import GenerateDownloadUrlResponse +from google.cloud.functions_v1.types.functions import GenerateUploadUrlRequest +from google.cloud.functions_v1.types.functions import GenerateUploadUrlResponse +from google.cloud.functions_v1.types.functions import GetFunctionRequest +from google.cloud.functions_v1.types.functions import HttpsTrigger +from google.cloud.functions_v1.types.functions import ListFunctionsRequest +from google.cloud.functions_v1.types.functions import ListFunctionsResponse +from google.cloud.functions_v1.types.functions import SecretEnvVar +from google.cloud.functions_v1.types.functions import SecretVolume +from google.cloud.functions_v1.types.functions import SourceRepository +from google.cloud.functions_v1.types.functions import UpdateFunctionRequest +from google.cloud.functions_v1.types.functions import CloudFunctionStatus +from google.cloud.functions_v1.types.operations import OperationMetadataV1 +from google.cloud.functions_v1.types.operations import OperationType + +__all__ = ('CloudFunctionsServiceClient', + 'CloudFunctionsServiceAsyncClient', + 'CallFunctionRequest', + 'CallFunctionResponse', + 'CloudFunction', + 'CreateFunctionRequest', + 'DeleteFunctionRequest', + 'EventTrigger', + 'FailurePolicy', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GetFunctionRequest', + 'HttpsTrigger', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'SecretEnvVar', + 'SecretVolume', + 'SourceRepository', + 'UpdateFunctionRequest', + 'CloudFunctionStatus', + 'OperationMetadataV1', + 'OperationType', +) diff --git a/owl-bot-staging/v1/google/cloud/functions/py.typed b/owl-bot-staging/v1/google/cloud/functions/py.typed new file mode 100644 index 0000000..982ebb1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py new file mode 100644 index 0000000..87351c6 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py @@ -0,0 +1,68 @@ +# -*- 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.cloud_functions_service import CloudFunctionsServiceClient +from .services.cloud_functions_service import CloudFunctionsServiceAsyncClient + +from .types.functions import CallFunctionRequest +from .types.functions import CallFunctionResponse +from .types.functions import CloudFunction +from .types.functions import CreateFunctionRequest +from .types.functions import DeleteFunctionRequest +from .types.functions import EventTrigger +from .types.functions import FailurePolicy +from .types.functions import GenerateDownloadUrlRequest +from .types.functions import GenerateDownloadUrlResponse +from .types.functions import GenerateUploadUrlRequest +from .types.functions import GenerateUploadUrlResponse +from .types.functions import GetFunctionRequest +from .types.functions import HttpsTrigger +from .types.functions import ListFunctionsRequest +from .types.functions import ListFunctionsResponse +from .types.functions import SecretEnvVar +from .types.functions import SecretVolume +from .types.functions import SourceRepository +from .types.functions import UpdateFunctionRequest +from .types.functions import CloudFunctionStatus +from .types.operations import OperationMetadataV1 +from .types.operations import OperationType + +__all__ = ( + 'CloudFunctionsServiceAsyncClient', +'CallFunctionRequest', +'CallFunctionResponse', +'CloudFunction', +'CloudFunctionStatus', +'CloudFunctionsServiceClient', +'CreateFunctionRequest', +'DeleteFunctionRequest', +'EventTrigger', +'FailurePolicy', +'GenerateDownloadUrlRequest', +'GenerateDownloadUrlResponse', +'GenerateUploadUrlRequest', +'GenerateUploadUrlResponse', +'GetFunctionRequest', +'HttpsTrigger', +'ListFunctionsRequest', +'ListFunctionsResponse', +'OperationMetadataV1', +'OperationType', +'SecretEnvVar', +'SecretVolume', +'SourceRepository', +'UpdateFunctionRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json new file mode 100644 index 0000000..5745d05 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json @@ -0,0 +1,133 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.functions_v1", + "protoPackage": "google.cloud.functions.v1", + "schema": "1.0", + "services": { + "CloudFunctionsService": { + "clients": { + "grpc": { + "libraryClient": "CloudFunctionsServiceClient", + "rpcs": { + "CallFunction": { + "methods": [ + "call_function" + ] + }, + "CreateFunction": { + "methods": [ + "create_function" + ] + }, + "DeleteFunction": { + "methods": [ + "delete_function" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "generate_download_url" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "generate_upload_url" + ] + }, + "GetFunction": { + "methods": [ + "get_function" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListFunctions": { + "methods": [ + "list_functions" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFunction": { + "methods": [ + "update_function" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudFunctionsServiceAsyncClient", + "rpcs": { + "CallFunction": { + "methods": [ + "call_function" + ] + }, + "CreateFunction": { + "methods": [ + "create_function" + ] + }, + "DeleteFunction": { + "methods": [ + "delete_function" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "generate_download_url" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "generate_upload_url" + ] + }, + "GetFunction": { + "methods": [ + "get_function" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListFunctions": { + "methods": [ + "list_functions" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFunction": { + "methods": [ + "update_function" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/py.typed b/owl-bot-staging/v1/google/cloud/functions_v1/py.typed new file mode 100644 index 0000000..982ebb1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/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/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py new file mode 100644 index 0000000..d784dc7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__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 CloudFunctionsServiceClient +from .async_client import CloudFunctionsServiceAsyncClient + +__all__ = ( + 'CloudFunctionsServiceClient', + 'CloudFunctionsServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py new file mode 100644 index 0000000..3010041 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py @@ -0,0 +1,1423 @@ +# -*- 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_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.functions_v1.services.cloud_functions_service import pagers +from google.cloud.functions_v1.types import functions +from google.cloud.functions_v1.types import operations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport +from .client import CloudFunctionsServiceClient + + +class CloudFunctionsServiceAsyncClient: + """A service that application uses to manipulate triggers and + functions. + """ + + _client: CloudFunctionsServiceClient + + DEFAULT_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT + + cloud_function_path = staticmethod(CloudFunctionsServiceClient.cloud_function_path) + parse_cloud_function_path = staticmethod(CloudFunctionsServiceClient.parse_cloud_function_path) + crypto_key_path = staticmethod(CloudFunctionsServiceClient.crypto_key_path) + parse_crypto_key_path = staticmethod(CloudFunctionsServiceClient.parse_crypto_key_path) + repository_path = staticmethod(CloudFunctionsServiceClient.repository_path) + parse_repository_path = staticmethod(CloudFunctionsServiceClient.parse_repository_path) + common_billing_account_path = staticmethod(CloudFunctionsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CloudFunctionsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CloudFunctionsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CloudFunctionsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CloudFunctionsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CloudFunctionsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CloudFunctionsServiceClient.common_project_path) + parse_common_project_path = staticmethod(CloudFunctionsServiceClient.parse_common_project_path) + common_location_path = staticmethod(CloudFunctionsServiceClient.common_location_path) + parse_common_location_path = staticmethod(CloudFunctionsServiceClient.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: + CloudFunctionsServiceAsyncClient: The constructed client. + """ + return CloudFunctionsServiceClient.from_service_account_info.__func__(CloudFunctionsServiceAsyncClient, 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: + CloudFunctionsServiceAsyncClient: The constructed client. + """ + return CloudFunctionsServiceClient.from_service_account_file.__func__(CloudFunctionsServiceAsyncClient, 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 CloudFunctionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CloudFunctionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CloudFunctionsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CloudFunctionsServiceClient).get_transport_class, type(CloudFunctionsServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CloudFunctionsServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud functions service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CloudFunctionsServiceTransport]): 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 = CloudFunctionsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_functions(self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsAsyncPager: + r"""Returns a list of functions that belong to the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): + The request object. Request for the `ListFunctions` + 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager: + Response for the ListFunctions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = functions.ListFunctionsRequest(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.list_functions, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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.ListFunctionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_function(self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CloudFunction: + r"""Returns a function with the given name from the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): + The request object. Request for the `GetFunction` + method. + name (:class:`str`): + Required. The name of the function + which details should be obtained. + + 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.functions_v1.types.CloudFunction: + Describes a Cloud Function that + contains user computation executed in + response to an event. It encapsulate + function and triggers configurations. + + """ + # 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 = functions.GetFunctionRequest(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_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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 create_function(self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + location: str = None, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): + The request object. Request for the `CreateFunction` + method. + location (:class:`str`): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``location`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function (:class:`google.cloud.functions_v1.types.CloudFunction`): + Required. Function to be created. + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([location, function]) + if request is 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 = functions.CreateFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if location is not None: + request.location = location + if function is not None: + request.function = function + + # 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_function, + default_timeout=600.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(( + ("location", request.location), + )), + ) + + # 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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def update_function(self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates existing function. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): + The request object. Request for the `UpdateFunction` + method. + function (:class:`google.cloud.functions_v1.types.CloudFunction`): + Required. New version of the + function. + + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([function]) + if request is 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 = functions.UpdateFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if function is not None: + request.function = function + + # 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_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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(( + ("function.name", request.function.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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def delete_function(self, + request: Union[functions.DeleteFunctionRequest, 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 function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): + The request object. Request for the `DeleteFunction` + method. + name (:class:`str`): + Required. The name of the function + which should be deleted. + + 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.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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 = functions.DeleteFunctionRequest(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_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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, + empty_pb2.Empty, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def call_function(self, + request: Union[functions.CallFunctionRequest, dict] = None, + *, + name: str = None, + data: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CallFunctionResponse: + r"""Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = await client.call_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): + The request object. Request for the `CallFunction` + method. + name (:class:`str`): + Required. The name of the function to + be called. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (:class:`str`): + Required. Input to be passed to the + function. + + This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: + Response of CallFunction method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, data]) + if request is 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 = functions.CallFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.call_function, + default_timeout=600.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 generate_upload_url(self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: + r"""Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = await client.generate_upload_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): + The request object. Request of `GenerateSourceUploadUrl` + 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.cloud.functions_v1.types.GenerateUploadUrlResponse: + Response of GenerateSourceUploadUrl method. + """ + # Create or coerce a protobuf request object. + request = functions.GenerateUploadUrlRequest(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.generate_upload_url, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_download_url(self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: + r"""Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = await client.generate_download_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): + The request object. Request of `GenerateDownloadUrl` + 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: + Response of GenerateDownloadUrl method. + """ + # Create or coerce a protobuf request object. + request = functions.GenerateDownloadUrlRequest(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.generate_download_url, + 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 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 on the specified + function. Replaces any existing policy. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await 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 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"""Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await 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 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"""Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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) + + 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-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CloudFunctionsServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py new file mode 100644 index 0000000..53c6f1a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py @@ -0,0 +1,1613 @@ +# -*- 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_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.functions_v1.services.cloud_functions_service import pagers +from google.cloud.functions_v1.types import functions +from google.cloud.functions_v1.types import operations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CloudFunctionsServiceGrpcTransport +from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport + + +class CloudFunctionsServiceClientMeta(type): + """Metaclass for the CloudFunctionsService 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[CloudFunctionsServiceTransport]] + _transport_registry["grpc"] = CloudFunctionsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CloudFunctionsServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CloudFunctionsServiceTransport]: + """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 CloudFunctionsServiceClient(metaclass=CloudFunctionsServiceClientMeta): + """A service that application uses to manipulate triggers and + functions. + """ + + @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 = "cloudfunctions.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: + CloudFunctionsServiceClient: 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: + CloudFunctionsServiceClient: 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) -> CloudFunctionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CloudFunctionsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def cloud_function_path(project: str,location: str,function: str,) -> str: + """Returns a fully-qualified cloud_function string.""" + return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + + @staticmethod + def parse_cloud_function_path(path: str) -> Dict[str,str]: + """Parses a cloud_function path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?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 repository_path(project: str,location: str,repository: str,) -> str: + """Returns a fully-qualified repository string.""" + return "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) + + @staticmethod + def parse_repository_path(path: str) -> Dict[str,str]: + """Parses a repository path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/repositories/(?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, CloudFunctionsServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud functions service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CloudFunctionsServiceTransport]): 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, CloudFunctionsServiceTransport): + # transport is a CloudFunctionsServiceTransport 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, + api_audience=client_options.api_audience, + ) + + def list_functions(self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsPager: + r"""Returns a list of functions that belong to the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): + The request object. Request for the `ListFunctions` + 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager: + Response for the ListFunctions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.ListFunctionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.ListFunctionsRequest): + request = functions.ListFunctionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_functions] + + # 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.ListFunctionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_function(self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CloudFunction: + r"""Returns a function with the given name from the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = client.get_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): + The request object. Request for the `GetFunction` + method. + name (str): + Required. The name of the function + which details should be obtained. + + 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.functions_v1.types.CloudFunction: + Describes a Cloud Function that + contains user computation executed in + response to an event. It encapsulate + function and triggers configurations. + + """ + # 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 functions.GetFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GetFunctionRequest): + request = functions.GetFunctionRequest(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_function] + + # 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 create_function(self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + location: str = None, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): + The request object. Request for the `CreateFunction` + method. + location (str): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``location`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function (google.cloud.functions_v1.types.CloudFunction): + Required. Function to be created. + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([location, function]) + if request is 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 functions.CreateFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.CreateFunctionRequest): + request = functions.CreateFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if location is not None: + request.location = location + if function is not None: + request.function = function + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("location", request.location), + )), + ) + + # 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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def update_function(self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates existing function. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): + The request object. Request for the `UpdateFunction` + method. + function (google.cloud.functions_v1.types.CloudFunction): + Required. New version of the + function. + + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([function]) + if request is 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 functions.UpdateFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.UpdateFunctionRequest): + request = functions.UpdateFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if function is not None: + request.function = function + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("function.name", request.function.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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def delete_function(self, + request: Union[functions.DeleteFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): + The request object. Request for the `DeleteFunction` + method. + name (str): + Required. The name of the function + which should be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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 functions.DeleteFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.DeleteFunctionRequest): + request = functions.DeleteFunctionRequest(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_function] + + # 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, + empty_pb2.Empty, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def call_function(self, + request: Union[functions.CallFunctionRequest, dict] = None, + *, + name: str = None, + data: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CallFunctionResponse: + r"""Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = client.call_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): + The request object. Request for the `CallFunction` + method. + name (str): + Required. The name of the function to + be called. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (str): + Required. Input to be passed to the + function. + + This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: + Response of CallFunction method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, data]) + if request is 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 functions.CallFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.CallFunctionRequest): + request = functions.CallFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.call_function] + + # 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 generate_upload_url(self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: + r"""Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = client.generate_upload_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): + The request object. Request of `GenerateSourceUploadUrl` + 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.cloud.functions_v1.types.GenerateUploadUrlResponse: + Response of GenerateSourceUploadUrl method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.GenerateUploadUrlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GenerateUploadUrlRequest): + request = functions.GenerateUploadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_upload_url] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_download_url(self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: + r"""Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = client.generate_download_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): + The request object. Request of `GenerateDownloadUrl` + 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: + Response of GenerateDownloadUrl method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.GenerateDownloadUrlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GenerateDownloadUrlRequest): + request = functions.GenerateDownloadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_download_url] + + # 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 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 on the specified + function. Replaces any existing policy. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 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"""Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 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"""Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CloudFunctionsServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py new file mode 100644 index 0000000..f31d4f1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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.functions_v1.types import functions + + +class ListFunctionsPager: + """A pager for iterating through ``list_functions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``functions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFunctions`` requests and continue to iterate + through the ``functions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` + 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[..., functions.ListFunctionsResponse], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + 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.functions_v1.types.ListFunctionsRequest): + The initial request object. + response (google.cloud.functions_v1.types.ListFunctionsResponse): + 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 = functions.ListFunctionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[functions.ListFunctionsResponse]: + 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[functions.CloudFunction]: + for page in self.pages: + yield from page.functions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFunctionsAsyncPager: + """A pager for iterating through ``list_functions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``functions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFunctions`` requests and continue to iterate + through the ``functions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` + 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[functions.ListFunctionsResponse]], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + 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.functions_v1.types.ListFunctionsRequest): + The initial request object. + response (google.cloud.functions_v1.types.ListFunctionsResponse): + 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 = functions.ListFunctionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[functions.ListFunctionsResponse]: + 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[functions.CloudFunction]: + async def async_generator(): + async for page in self.pages: + for response in page.functions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py new file mode 100644 index 0000000..ac1ba7e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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 CloudFunctionsServiceTransport +from .grpc import CloudFunctionsServiceGrpcTransport +from .grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CloudFunctionsServiceTransport]] +_transport_registry['grpc'] = CloudFunctionsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CloudFunctionsServiceGrpcAsyncIOTransport + +__all__ = ( + 'CloudFunctionsServiceTransport', + 'CloudFunctionsServiceGrpcTransport', + 'CloudFunctionsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py new file mode 100644 index 0000000..2d3352f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py @@ -0,0 +1,331 @@ +# -*- 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.functions_v1.types import functions +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-functions', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CloudFunctionsServiceTransport(abc.ABC): + """Abstract transport class for CloudFunctionsService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'cloudfunctions.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, + api_audience: Optional[str] = None, + **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. + """ + + 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) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_functions: gapic_v1.method.wrap_method( + self.list_functions, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_function: gapic_v1.method.wrap_method( + self.get_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.create_function: gapic_v1.method.wrap_method( + self.create_function, + default_timeout=600.0, + client_info=client_info, + ), + self.update_function: gapic_v1.method.wrap_method( + self.update_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_function: gapic_v1.method.wrap_method( + self.delete_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.call_function: gapic_v1.method.wrap_method( + self.call_function, + default_timeout=600.0, + client_info=client_info, + ), + self.generate_upload_url: gapic_v1.method.wrap_method( + self.generate_upload_url, + default_timeout=None, + client_info=client_info, + ), + self.generate_download_url: gapic_v1.method.wrap_method( + self.generate_download_url, + 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.get_iam_policy: gapic_v1.method.wrap_method( + self.get_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 list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + Union[ + functions.ListFunctionsResponse, + Awaitable[functions.ListFunctionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_function(self) -> Callable[ + [functions.GetFunctionRequest], + Union[ + functions.CloudFunction, + Awaitable[functions.CloudFunction] + ]]: + raise NotImplementedError() + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def call_function(self) -> Callable[ + [functions.CallFunctionRequest], + Union[ + functions.CallFunctionResponse, + Awaitable[functions.CallFunctionResponse] + ]]: + raise NotImplementedError() + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + Union[ + functions.GenerateUploadUrlResponse, + Awaitable[functions.GenerateUploadUrlResponse] + ]]: + raise NotImplementedError() + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Union[ + functions.GenerateDownloadUrlResponse, + Awaitable[functions.GenerateDownloadUrlResponse] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CloudFunctionsServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py new file mode 100644 index 0000000..92c02c9 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py @@ -0,0 +1,593 @@ +# -*- 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.functions_v1.types import functions +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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO + + +class CloudFunctionsServiceGrpcTransport(CloudFunctionsServiceTransport): + """gRPC backend transport for CloudFunctionsService. + + A service that application uses to manipulate triggers and + functions. + + 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 = 'cloudfunctions.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, + api_audience: Optional[str] = None, + ) -> 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, + api_audience=api_audience, + ) + + 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 = 'cloudfunctions.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 list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + functions.ListFunctionsResponse]: + r"""Return a callable for the list functions method over gRPC. + + Returns a list of functions that belong to the + requested project. + + Returns: + Callable[[~.ListFunctionsRequest], + ~.ListFunctionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_functions' not in self._stubs: + self._stubs['list_functions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', + request_serializer=functions.ListFunctionsRequest.serialize, + response_deserializer=functions.ListFunctionsResponse.deserialize, + ) + return self._stubs['list_functions'] + + @property + def get_function(self) -> Callable[ + [functions.GetFunctionRequest], + functions.CloudFunction]: + r"""Return a callable for the get function method over gRPC. + + Returns a function with the given name from the + requested project. + + Returns: + Callable[[~.GetFunctionRequest], + ~.CloudFunction]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_function' not in self._stubs: + self._stubs['get_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', + request_serializer=functions.GetFunctionRequest.serialize, + response_deserializer=functions.CloudFunction.deserialize, + ) + return self._stubs['get_function'] + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create function method over gRPC. + + Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + Returns: + Callable[[~.CreateFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['create_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', + request_serializer=functions.CreateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_function'] + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the update function method over gRPC. + + Updates existing function. + + Returns: + Callable[[~.UpdateFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['update_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', + request_serializer=functions.UpdateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_function'] + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete function method over gRPC. + + Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + Returns: + Callable[[~.DeleteFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['delete_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', + request_serializer=functions.DeleteFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_function'] + + @property + def call_function(self) -> Callable[ + [functions.CallFunctionRequest], + functions.CallFunctionResponse]: + r"""Return a callable for the call function method over gRPC. + + Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + Returns: + Callable[[~.CallFunctionRequest], + ~.CallFunctionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'call_function' not in self._stubs: + self._stubs['call_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', + request_serializer=functions.CallFunctionRequest.serialize, + response_deserializer=functions.CallFunctionResponse.deserialize, + ) + return self._stubs['call_function'] + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + functions.GenerateUploadUrlResponse]: + r"""Return a callable for the generate upload url method over gRPC. + + Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + Returns: + Callable[[~.GenerateUploadUrlRequest], + ~.GenerateUploadUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_upload_url' not in self._stubs: + self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', + request_serializer=functions.GenerateUploadUrlRequest.serialize, + response_deserializer=functions.GenerateUploadUrlResponse.deserialize, + ) + return self._stubs['generate_upload_url'] + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + functions.GenerateDownloadUrlResponse]: + r"""Return a callable for the generate download url method over gRPC. + + Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + Returns: + Callable[[~.GenerateDownloadUrlRequest], + ~.GenerateDownloadUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_download_url' not in self._stubs: + self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', + request_serializer=functions.GenerateDownloadUrlRequest.serialize, + response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, + ) + return self._stubs['generate_download_url'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/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__ = ( + 'CloudFunctionsServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..d05047d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py @@ -0,0 +1,592 @@ +# -*- 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.functions_v1.types import functions +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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CloudFunctionsServiceGrpcTransport + + +class CloudFunctionsServiceGrpcAsyncIOTransport(CloudFunctionsServiceTransport): + """gRPC AsyncIO backend transport for CloudFunctionsService. + + A service that application uses to manipulate triggers and + functions. + + 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 = 'cloudfunctions.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 = 'cloudfunctions.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, + api_audience: Optional[str] = None, + ) -> 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, + api_audience=api_audience, + ) + + 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 list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + Awaitable[functions.ListFunctionsResponse]]: + r"""Return a callable for the list functions method over gRPC. + + Returns a list of functions that belong to the + requested project. + + Returns: + Callable[[~.ListFunctionsRequest], + Awaitable[~.ListFunctionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_functions' not in self._stubs: + self._stubs['list_functions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', + request_serializer=functions.ListFunctionsRequest.serialize, + response_deserializer=functions.ListFunctionsResponse.deserialize, + ) + return self._stubs['list_functions'] + + @property + def get_function(self) -> Callable[ + [functions.GetFunctionRequest], + Awaitable[functions.CloudFunction]]: + r"""Return a callable for the get function method over gRPC. + + Returns a function with the given name from the + requested project. + + Returns: + Callable[[~.GetFunctionRequest], + Awaitable[~.CloudFunction]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_function' not in self._stubs: + self._stubs['get_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', + request_serializer=functions.GetFunctionRequest.serialize, + response_deserializer=functions.CloudFunction.deserialize, + ) + return self._stubs['get_function'] + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create function method over gRPC. + + Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + Returns: + Callable[[~.CreateFunctionRequest], + 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_function' not in self._stubs: + self._stubs['create_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', + request_serializer=functions.CreateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_function'] + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update function method over gRPC. + + Updates existing function. + + Returns: + Callable[[~.UpdateFunctionRequest], + 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_function' not in self._stubs: + self._stubs['update_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', + request_serializer=functions.UpdateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_function'] + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete function method over gRPC. + + Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + Returns: + Callable[[~.DeleteFunctionRequest], + 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_function' not in self._stubs: + self._stubs['delete_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', + request_serializer=functions.DeleteFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_function'] + + @property + def call_function(self) -> Callable[ + [functions.CallFunctionRequest], + Awaitable[functions.CallFunctionResponse]]: + r"""Return a callable for the call function method over gRPC. + + Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + Returns: + Callable[[~.CallFunctionRequest], + Awaitable[~.CallFunctionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'call_function' not in self._stubs: + self._stubs['call_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', + request_serializer=functions.CallFunctionRequest.serialize, + response_deserializer=functions.CallFunctionResponse.deserialize, + ) + return self._stubs['call_function'] + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + Awaitable[functions.GenerateUploadUrlResponse]]: + r"""Return a callable for the generate upload url method over gRPC. + + Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + Returns: + Callable[[~.GenerateUploadUrlRequest], + Awaitable[~.GenerateUploadUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_upload_url' not in self._stubs: + self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', + request_serializer=functions.GenerateUploadUrlRequest.serialize, + response_deserializer=functions.GenerateUploadUrlResponse.deserialize, + ) + return self._stubs['generate_upload_url'] + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Awaitable[functions.GenerateDownloadUrlResponse]]: + r"""Return a callable for the generate download url method over gRPC. + + Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + Returns: + Callable[[~.GenerateDownloadUrlRequest], + Awaitable[~.GenerateDownloadUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_download_url' not in self._stubs: + self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', + request_serializer=functions.GenerateDownloadUrlRequest.serialize, + response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, + ) + return self._stubs['generate_download_url'] + + @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 on the specified + function. Replaces 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.functions.v1.CloudFunctionsService/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + 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.functions.v1.CloudFunctionsService/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Returns: + Callable[[~.TestIamPermissionsRequest], + 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.functions.v1.CloudFunctionsService/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__ = ( + 'CloudFunctionsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py new file mode 100644 index 0000000..b09e206 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py @@ -0,0 +1,66 @@ +# -*- 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 .functions import ( + CallFunctionRequest, + CallFunctionResponse, + CloudFunction, + CreateFunctionRequest, + DeleteFunctionRequest, + EventTrigger, + FailurePolicy, + GenerateDownloadUrlRequest, + GenerateDownloadUrlResponse, + GenerateUploadUrlRequest, + GenerateUploadUrlResponse, + GetFunctionRequest, + HttpsTrigger, + ListFunctionsRequest, + ListFunctionsResponse, + SecretEnvVar, + SecretVolume, + SourceRepository, + UpdateFunctionRequest, + CloudFunctionStatus, +) +from .operations import ( + OperationMetadataV1, + OperationType, +) + +__all__ = ( + 'CallFunctionRequest', + 'CallFunctionResponse', + 'CloudFunction', + 'CreateFunctionRequest', + 'DeleteFunctionRequest', + 'EventTrigger', + 'FailurePolicy', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GetFunctionRequest', + 'HttpsTrigger', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'SecretEnvVar', + 'SecretVolume', + 'SourceRepository', + 'UpdateFunctionRequest', + 'CloudFunctionStatus', + 'OperationMetadataV1', + 'OperationType', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py new file mode 100644 index 0000000..844c961 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py @@ -0,0 +1,1067 @@ +# -*- 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 duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.functions.v1', + manifest={ + 'CloudFunctionStatus', + 'CloudFunction', + 'SourceRepository', + 'HttpsTrigger', + 'EventTrigger', + 'FailurePolicy', + 'SecretEnvVar', + 'SecretVolume', + 'CreateFunctionRequest', + 'UpdateFunctionRequest', + 'GetFunctionRequest', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'DeleteFunctionRequest', + 'CallFunctionRequest', + 'CallFunctionResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + }, +) + + +class CloudFunctionStatus(proto.Enum): + r"""Describes the current stage of a deployment.""" + CLOUD_FUNCTION_STATUS_UNSPECIFIED = 0 + ACTIVE = 1 + OFFLINE = 2 + DEPLOY_IN_PROGRESS = 3 + DELETE_IN_PROGRESS = 4 + UNKNOWN = 5 + + +class CloudFunction(proto.Message): + r"""Describes a Cloud Function that contains user computation + executed in response to an event. It encapsulate function and + triggers configurations. + + 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): + A user-defined name of the function. Function names must be + unique globally and match pattern + ``projects/*/locations/*/functions/*`` + description (str): + User-provided description of a function. + source_archive_url (str): + The Google Cloud Storage URL, starting with ``gs://``, + pointing to the zip archive which contains the function. + + This field is a member of `oneof`_ ``source_code``. + source_repository (google.cloud.functions_v1.types.SourceRepository): + **Beta Feature** + + The source repository where a function is hosted. + + This field is a member of `oneof`_ ``source_code``. + source_upload_url (str): + The Google Cloud Storage signed URL used for source + uploading, generated by calling + [google.cloud.functions.v1.GenerateUploadUrl]. + + The signature is validated on write methods (Create, Update) + The signature is stripped from the Function object on read + methods (Get, List) + + This field is a member of `oneof`_ ``source_code``. + https_trigger (google.cloud.functions_v1.types.HttpsTrigger): + An HTTPS endpoint type of source that can be + triggered via URL. + + This field is a member of `oneof`_ ``trigger``. + event_trigger (google.cloud.functions_v1.types.EventTrigger): + A source that fires events in response to a + condition in another service. + + This field is a member of `oneof`_ ``trigger``. + status (google.cloud.functions_v1.types.CloudFunctionStatus): + Output only. Status of the function + deployment. + entry_point (str): + The name of the function (as defined in source code) that + will be executed. Defaults to the resource name suffix, if + not specified. For backward compatibility, if function with + given name is not found, then the system will try to use + function named "function". For Node.js this is name of a + function exported by the module specified in + ``source_location``. + runtime (str): + The runtime in which to run the function. Required when + deploying a new function, optional when updating an existing + function. For a complete list of possible choices, see the + ```gcloud`` command + reference `__. + timeout (google.protobuf.duration_pb2.Duration): + The function execution timeout. Execution is + considered failed and can be terminated if the + function is not completed at the end of the + timeout period. Defaults to 60 seconds. + available_memory_mb (int): + The amount of memory in MB available for a + function. Defaults to 256MB. + service_account_email (str): + The email of the function's service account. If empty, + defaults to ``{project_id}@appspot.gserviceaccount.com``. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update timestamp of a + Cloud Function. + version_id (int): + Output only. The version identifier of the + Cloud Function. Each deployment attempt results + in a new version of a function being created. + labels (Mapping[str, str]): + Labels associated with this Cloud Function. + environment_variables (Mapping[str, str]): + Environment variables that shall be available + during function execution. + build_environment_variables (Mapping[str, str]): + Build environment variables that shall be + available during build time. + network (str): + The VPC Network that this cloud function can connect to. It + can be either the fully-qualified URI, or the short name of + the network resource. If the short network name is used, the + network must belong to the same project. Otherwise, it must + belong to a project within the same organization. The format + of this field is either + ``projects/{project}/global/networks/{network}`` or + ``{network}``, where ``{project}`` is a project id where the + network is defined, and ``{network}`` is the short name of + the network. + + This field is mutually exclusive with ``vpc_connector`` and + will be replaced by it. + + See `the VPC + documentation `__ + for more information on connecting Cloud projects. + max_instances (int): + The limit on the maximum number of function instances that + may coexist at a given time. + + In some cases, such as rapid traffic surges, Cloud Functions + may, for a short period of time, create more instances than + the specified max instances limit. If your function cannot + tolerate this temporary behavior, you may want to factor in + a safety margin and set a lower max instances value than + your function can tolerate. + + See the `Max + Instances `__ + Guide for more details. + min_instances (int): + A lower bound for the number function + instances that may coexist at a given time. + vpc_connector (str): + The VPC Network Connector that this cloud function can + connect to. It can be either the fully-qualified URI, or the + short name of the network connector resource. The format of + this field is ``projects/*/locations/*/connectors/*`` + + This field is mutually exclusive with ``network`` field and + will eventually replace it. + + See `the VPC + documentation `__ + for more information on connecting Cloud projects. + vpc_connector_egress_settings (google.cloud.functions_v1.types.CloudFunction.VpcConnectorEgressSettings): + The egress settings for the connector, + controlling what traffic is diverted through it. + ingress_settings (google.cloud.functions_v1.types.CloudFunction.IngressSettings): + The ingress settings for the function, + controlling what traffic can reach it. + kms_key_name (str): + Resource name of a KMS crypto key (managed by the user) used + to encrypt/decrypt function resources. + + It must match the pattern + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. + + If specified, you must also provide an artifact registry + repository using the ``docker_repository`` field that was + created with the same KMS crypto key. + + The following service accounts need to be granted the role + 'Cloud KMS CryptoKey Encrypter/Decrypter + (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the + Key/KeyRing/Project/Organization (least access preferred). + + 1. Google Cloud Functions service account + (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) + - Required to protect the function's image. + 2. Google Storage service account + (service-{project_number}@gs-project-accounts.iam.gserviceaccount.com) + - Required to protect the function's source code. If this + service account does not exist, deploying a function + without a KMS key or retrieving the service agent name + provisions it. For more information, see + https://cloud.google.com/storage/docs/projects#service-agents + and + https://cloud.google.com/storage/docs/getting-service-agent#gsutil. + + Google Cloud Functions delegates access to service agents to + protect function resources in internal projects that are not + accessible by the end user. + build_worker_pool (str): + Name of the Cloud Build Custom Worker Pool that should be + used to build the function. The format of this field is + ``projects/{project}/locations/{region}/workerPools/{workerPool}`` + where ``{project}`` and ``{region}`` are the project id and + region respectively where the worker pool is defined and + ``{workerPool}`` is the short name of the worker pool. + + If the project id is not the same as the function, then the + Cloud Functions Service Agent + (``service-@gcf-admin-robot.iam.gserviceaccount.com``) + must be granted the role Cloud Build Custom Workers Builder + (``roles/cloudbuild.customworkers.builder``) in the project. + build_id (str): + Output only. The Cloud Build ID of the latest + successful deployment of the function. + build_name (str): + Output only. The Cloud Build Name of the function + deployment. + ``projects//locations//builds/``. + secret_environment_variables (Sequence[google.cloud.functions_v1.types.SecretEnvVar]): + Secret environment variables configuration. + secret_volumes (Sequence[google.cloud.functions_v1.types.SecretVolume]): + Secret volumes configuration. + source_token (str): + Input only. An identifier for Firebase + function sources. Disclaimer: This field is only + supported for Firebase function deployments. + docker_repository (str): + User managed repository created in Artifact Registry + optionally with a customer managed encryption key. If + specified, deployments will use Artifact Registry. If + unspecified and the deployment is eligible to use Artifact + Registry, GCF will create and use a repository named + 'gcf-artifacts' for every deployed region. This is the + repository to which the function docker image will be pushed + after it is built by Cloud Build. + + It must match the pattern + ``projects/{project}/locations/{location}/repositories/{repository}``. + + Cross-project repositories are not supported. Cross-location + repositories are not supported. Repository format must be + 'DOCKER'. + docker_registry (google.cloud.functions_v1.types.CloudFunction.DockerRegistry): + Docker Registry to use for this deployment. + + If ``docker_repository`` field is specified, this field will + be automatically set as ``ARTIFACT_REGISTRY``. If + unspecified, it currently defaults to + ``CONTAINER_REGISTRY``. This field may be overridden by the + backend for eligible deployments. + """ + class VpcConnectorEgressSettings(proto.Enum): + r"""Available egress settings. + + This controls what traffic is diverted through the VPC Access + Connector resource. By default PRIVATE_RANGES_ONLY will be used. + """ + VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED = 0 + PRIVATE_RANGES_ONLY = 1 + ALL_TRAFFIC = 2 + + class IngressSettings(proto.Enum): + r"""Available ingress settings. + + This controls what traffic can reach the function. + + If unspecified, ALLOW_ALL will be used. + """ + INGRESS_SETTINGS_UNSPECIFIED = 0 + ALLOW_ALL = 1 + ALLOW_INTERNAL_ONLY = 2 + ALLOW_INTERNAL_AND_GCLB = 3 + + class DockerRegistry(proto.Enum): + r"""Docker Registry to use for storing function Docker images.""" + DOCKER_REGISTRY_UNSPECIFIED = 0 + CONTAINER_REGISTRY = 1 + ARTIFACT_REGISTRY = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + source_archive_url = proto.Field( + proto.STRING, + number=3, + oneof='source_code', + ) + source_repository = proto.Field( + proto.MESSAGE, + number=4, + oneof='source_code', + message='SourceRepository', + ) + source_upload_url = proto.Field( + proto.STRING, + number=16, + oneof='source_code', + ) + https_trigger = proto.Field( + proto.MESSAGE, + number=5, + oneof='trigger', + message='HttpsTrigger', + ) + event_trigger = proto.Field( + proto.MESSAGE, + number=6, + oneof='trigger', + message='EventTrigger', + ) + status = proto.Field( + proto.ENUM, + number=7, + enum='CloudFunctionStatus', + ) + entry_point = proto.Field( + proto.STRING, + number=8, + ) + runtime = proto.Field( + proto.STRING, + number=19, + ) + timeout = proto.Field( + proto.MESSAGE, + number=9, + message=duration_pb2.Duration, + ) + available_memory_mb = proto.Field( + proto.INT32, + number=10, + ) + service_account_email = proto.Field( + proto.STRING, + number=11, + ) + update_time = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + version_id = proto.Field( + proto.INT64, + number=14, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=15, + ) + environment_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=17, + ) + build_environment_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=28, + ) + network = proto.Field( + proto.STRING, + number=18, + ) + max_instances = proto.Field( + proto.INT32, + number=20, + ) + min_instances = proto.Field( + proto.INT32, + number=32, + ) + vpc_connector = proto.Field( + proto.STRING, + number=22, + ) + vpc_connector_egress_settings = proto.Field( + proto.ENUM, + number=23, + enum=VpcConnectorEgressSettings, + ) + ingress_settings = proto.Field( + proto.ENUM, + number=24, + enum=IngressSettings, + ) + kms_key_name = proto.Field( + proto.STRING, + number=25, + ) + build_worker_pool = proto.Field( + proto.STRING, + number=26, + ) + build_id = proto.Field( + proto.STRING, + number=27, + ) + build_name = proto.Field( + proto.STRING, + number=33, + ) + secret_environment_variables = proto.RepeatedField( + proto.MESSAGE, + number=29, + message='SecretEnvVar', + ) + secret_volumes = proto.RepeatedField( + proto.MESSAGE, + number=30, + message='SecretVolume', + ) + source_token = proto.Field( + proto.STRING, + number=31, + ) + docker_repository = proto.Field( + proto.STRING, + number=34, + ) + docker_registry = proto.Field( + proto.ENUM, + number=35, + enum=DockerRegistry, + ) + + +class SourceRepository(proto.Message): + r"""Describes SourceRepository, used to represent parameters + related to source repository where a function is hosted. + + Attributes: + url (str): + The URL pointing to the hosted repository where the function + is defined. There are supported Cloud Source Repository URLs + in the following formats: + + To refer to a specific commit: + ``https://source.developers.google.com/projects/*/repos/*/revisions/*/paths/*`` + To refer to a moveable alias (branch): + ``https://source.developers.google.com/projects/*/repos/*/moveable-aliases/*/paths/*`` + In particular, to refer to HEAD use ``master`` moveable + alias. To refer to a specific fixed alias (tag): + ``https://source.developers.google.com/projects/*/repos/*/fixed-aliases/*/paths/*`` + + You may omit ``paths/*`` if you want to use the main + directory. + deployed_url (str): + Output only. The URL pointing to the hosted + repository where the function were defined at + the time of deployment. It always points to a + specific commit in the format described above. + """ + + url = proto.Field( + proto.STRING, + number=1, + ) + deployed_url = proto.Field( + proto.STRING, + number=2, + ) + + +class HttpsTrigger(proto.Message): + r"""Describes HttpsTrigger, could be used to connect web hooks to + function. + + Attributes: + url (str): + Output only. The deployed url for the + function. + security_level (google.cloud.functions_v1.types.HttpsTrigger.SecurityLevel): + The security level for the function. + """ + class SecurityLevel(proto.Enum): + r"""Available security level settings. + + This controls the methods to enforce security (HTTPS) on a URL. + + If unspecified, SECURE_OPTIONAL will be used. + """ + SECURITY_LEVEL_UNSPECIFIED = 0 + SECURE_ALWAYS = 1 + SECURE_OPTIONAL = 2 + + url = proto.Field( + proto.STRING, + number=1, + ) + security_level = proto.Field( + proto.ENUM, + number=2, + enum=SecurityLevel, + ) + + +class EventTrigger(proto.Message): + r"""Describes EventTrigger, used to request events be sent from + another service. + + Attributes: + event_type (str): + Required. The type of event to observe. For example: + ``providers/cloud.storage/eventTypes/object.change`` and + ``providers/cloud.pubsub/eventTypes/topic.publish``. + + Event types match pattern ``providers/*/eventTypes/*.*``. + The pattern contains: + + 1. namespace: For example, ``cloud.storage`` and + ``google.firebase.analytics``. + 2. resource type: The type of resource on which event + occurs. For example, the Google Cloud Storage API + includes the type ``object``. + 3. action: The action that generates the event. For example, + action for a Google Cloud Storage Object is 'change'. + These parts are lower case. + resource (str): + Required. The resource(s) from which to observe events, for + example, ``projects/_/buckets/myBucket``. + + Not all syntactically correct values are accepted by all + services. For example: + + 1. The authorization model must support it. Google Cloud + Functions only allows EventTriggers to be deployed that + observe resources in the same project as the + ``CloudFunction``. + 2. The resource type must match the pattern expected for an + ``event_type``. For example, an ``EventTrigger`` that has + an ``event_type`` of "google.pubsub.topic.publish" should + have a resource that matches Google Cloud Pub/Sub topics. + + Additionally, some services may support short names when + creating an ``EventTrigger``. These will always be returned + in the normalized "long" format. + + See each *service's* documentation for supported formats. + service (str): + The hostname of the service that should be observed. + + If no string is provided, the default service implementing + the API will be used. For example, + ``storage.googleapis.com`` is the default for all event + types in the ``google.storage`` namespace. + failure_policy (google.cloud.functions_v1.types.FailurePolicy): + Specifies policy for failed executions. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + resource = proto.Field( + proto.STRING, + number=2, + ) + service = proto.Field( + proto.STRING, + number=3, + ) + failure_policy = proto.Field( + proto.MESSAGE, + number=5, + message='FailurePolicy', + ) + + +class FailurePolicy(proto.Message): + r"""Describes the policy in case of function's execution failure. + If empty, then defaults to ignoring failures (i.e. not retrying + them). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + retry (google.cloud.functions_v1.types.FailurePolicy.Retry): + If specified, then the function will be + retried in case of a failure. + + This field is a member of `oneof`_ ``action``. + """ + + class Retry(proto.Message): + r"""Describes the retry policy in case of function's execution + failure. A function execution will be retried on any failure. A + failed execution will be retried up to 7 days with an + exponential backoff (capped at 10 seconds). + Retried execution is charged as any other execution. + + """ + + retry = proto.Field( + proto.MESSAGE, + number=1, + oneof='action', + message=Retry, + ) + + +class SecretEnvVar(proto.Message): + r"""Configuration for a secret environment variable. It has the + information necessary to fetch the secret value from secret + manager and expose it as an environment variable. + + Attributes: + key (str): + Name of the environment variable. + project_id (str): + Project identifier (preferrably project + number but can also be the project ID) of the + project that contains the secret. If not set, it + will be populated with the function's project + assuming that the secret exists in the same + project as of the function. + secret (str): + Name of the secret in secret manager (not the + full resource name). + version (str): + Version of the secret (version number or the + string 'latest'). It is recommended to use a + numeric version for secret environment variables + as any updates to the secret value is not + reflected until new instances start. + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + secret = proto.Field( + proto.STRING, + number=3, + ) + version = proto.Field( + proto.STRING, + number=4, + ) + + +class SecretVolume(proto.Message): + r"""Configuration for a secret volume. It has the information + necessary to fetch the secret value from secret manager and make + it available as files mounted at the requested paths within the + application container. Secret value is not a part of the + configuration. Every filesystem read operation performs a lookup + in secret manager to retrieve the secret value. + + Attributes: + mount_path (str): + The path within the container to mount the secret volume. + For example, setting the mount_path as ``/etc/secrets`` + would mount the secret value files under the + ``/etc/secrets`` directory. This directory will also be + completely shadowed and unavailable to mount any other + secrets. + + Recommended mount paths: /etc/secrets Restricted mount + paths: /cloudsql, /dev/log, /pod, /proc, /var/log + project_id (str): + Project identifier (preferrably project + number but can also be the project ID) of the + project that contains the secret. If not set, it + will be populated with the function's project + assuming that the secret exists in the same + project as of the function. + secret (str): + Name of the secret in secret manager (not the + full resource name). + versions (Sequence[google.cloud.functions_v1.types.SecretVolume.SecretVersion]): + List of secret versions to mount for this secret. If empty, + the ``latest`` version of the secret will be made available + in a file named after the secret under the mount point. + """ + + class SecretVersion(proto.Message): + r"""Configuration for a single version. + + Attributes: + version (str): + Version of the secret (version number or the string + 'latest'). It is preferrable to use ``latest`` version with + secret volumes as secret value changes are reflected + immediately. + path (str): + Relative path of the file under the mount path where the + secret value for this version will be fetched and made + available. For example, setting the mount_path as + '/etc/secrets' and path as ``/secret_foo`` would mount the + secret value file at ``/etc/secrets/secret_foo``. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + path = proto.Field( + proto.STRING, + number=2, + ) + + mount_path = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + secret = proto.Field( + proto.STRING, + number=3, + ) + versions = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=SecretVersion, + ) + + +class CreateFunctionRequest(proto.Message): + r"""Request for the ``CreateFunction`` method. + + Attributes: + location (str): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + function (google.cloud.functions_v1.types.CloudFunction): + Required. Function to be created. + """ + + location = proto.Field( + proto.STRING, + number=1, + ) + function = proto.Field( + proto.MESSAGE, + number=2, + message='CloudFunction', + ) + + +class UpdateFunctionRequest(proto.Message): + r"""Request for the ``UpdateFunction`` method. + + Attributes: + function (google.cloud.functions_v1.types.CloudFunction): + Required. New version of the function. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields in ``CloudFunction`` that have + to be updated. + """ + + function = proto.Field( + proto.MESSAGE, + number=1, + message='CloudFunction', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetFunctionRequest(proto.Message): + r"""Request for the ``GetFunction`` method. + + Attributes: + name (str): + Required. The name of the function which + details should be obtained. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFunctionsRequest(proto.Message): + r"""Request for the ``ListFunctions`` method. + + Attributes: + parent (str): + The project and location from which the function should be + listed, specified in the format ``projects/*/locations/*`` + If you want to list functions in all locations, use "-" in + place of a location. When listing functions in all + locations, if one or more location(s) are unreachable, the + response will contain functions from all reachable locations + along with the names of any unreachable locations. + page_size (int): + Maximum number of functions to return per + call. + page_token (str): + The value returned by the last ``ListFunctionsResponse``; + indicates that this is a continuation of a prior + ``ListFunctions`` call, and that the system should return + the next page of data. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListFunctionsResponse(proto.Message): + r"""Response for the ``ListFunctions`` method. + + Attributes: + functions (Sequence[google.cloud.functions_v1.types.CloudFunction]): + The functions that match the request. + next_page_token (str): + If not empty, indicates that there may be more functions + that match the request; this value should be passed in a new + [google.cloud.functions.v1.ListFunctionsRequest][google.cloud.functions.v1.ListFunctionsRequest] + to get more functions. + unreachable (Sequence[str]): + Locations that could not be reached. The + response does not include any functions from + these locations. + """ + + @property + def raw_page(self): + return self + + functions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CloudFunction', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + unreachable = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DeleteFunctionRequest(proto.Message): + r"""Request for the ``DeleteFunction`` method. + + Attributes: + name (str): + Required. The name of the function which + should be deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CallFunctionRequest(proto.Message): + r"""Request for the ``CallFunction`` method. + + Attributes: + name (str): + Required. The name of the function to be + called. + data (str): + Required. Input to be passed to the function. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + data = proto.Field( + proto.STRING, + number=2, + ) + + +class CallFunctionResponse(proto.Message): + r"""Response of ``CallFunction`` method. + + Attributes: + execution_id (str): + Execution id of function invocation. + result (str): + Result populated for successful execution of + synchronous function. Will not be populated if + function does not return a result through + context. + error (str): + Either system or user-function generated + error. Set if execution was not successful. + """ + + execution_id = proto.Field( + proto.STRING, + number=1, + ) + result = proto.Field( + proto.STRING, + number=2, + ) + error = proto.Field( + proto.STRING, + number=3, + ) + + +class GenerateUploadUrlRequest(proto.Message): + r"""Request of ``GenerateSourceUploadUrl`` method. + + Attributes: + parent (str): + The project and location in which the Google Cloud Storage + signed URL should be generated, specified in the format + ``projects/*/locations/*``. + kms_key_name (str): + Resource name of a KMS crypto key (managed by the user) used + to encrypt/decrypt function source code objects in staging + Cloud Storage buckets. When you generate an upload url and + upload your source code, it gets copied to a staging Cloud + Storage bucket in an internal regional project. The source + code is then copied to a versioned directory in the sources + bucket in the consumer project during the function + deployment. + + It must match the pattern + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. + + The Google Cloud Functions service account + (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) + must be granted the role 'Cloud KMS CryptoKey + Encrypter/Decrypter + (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the + Key/KeyRing/Project/Organization (least access preferred). + GCF will delegate access to the Google Storage service + account in the internal project. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + kms_key_name = proto.Field( + proto.STRING, + number=2, + ) + + +class GenerateUploadUrlResponse(proto.Message): + r"""Response of ``GenerateSourceUploadUrl`` method. + + Attributes: + upload_url (str): + The generated Google Cloud Storage signed URL + that should be used for a function source code + upload. The uploaded file should be a zip + archive which contains a function. + """ + + upload_url = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateDownloadUrlRequest(proto.Message): + r"""Request of ``GenerateDownloadUrl`` method. + + Attributes: + name (str): + The name of function for which source code + Google Cloud Storage signed URL should be + generated. + version_id (int): + The optional version of function. If not set, + default, current version is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + version_id = proto.Field( + proto.UINT64, + number=2, + ) + + +class GenerateDownloadUrlResponse(proto.Message): + r"""Response of ``GenerateDownloadUrl`` method. + + Attributes: + download_url (str): + The generated Google Cloud Storage signed URL + that should be used for function source code + download. + """ + + download_url = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py new file mode 100644 index 0000000..ab59796 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py @@ -0,0 +1,108 @@ +# -*- 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 any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.functions.v1', + manifest={ + 'OperationType', + 'OperationMetadataV1', + }, +) + + +class OperationType(proto.Enum): + r"""A type of an operation.""" + OPERATION_UNSPECIFIED = 0 + CREATE_FUNCTION = 1 + UPDATE_FUNCTION = 2 + DELETE_FUNCTION = 3 + + +class OperationMetadataV1(proto.Message): + r"""Metadata describing an [Operation][google.longrunning.Operation] + + Attributes: + target (str): + Target of the operation - for example + ``projects/project-1/locations/region-1/functions/function-1`` + type_ (google.cloud.functions_v1.types.OperationType): + Type of operation. + request (google.protobuf.any_pb2.Any): + The original request that started the + operation. + version_id (int): + Version id of the function created or updated + by an API call. This field is only populated for + Create and Update operations. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update timestamp of the operation. + build_id (str): + The Cloud Build ID of the function created or + updated by an API call. This field is only + populated for Create and Update operations. + source_token (str): + An identifier for Firebase function sources. + Disclaimer: This field is only supported for + Firebase function deployments. + build_name (str): + The Cloud Build Name of the function deployment. This field + is only populated for Create and Update operations. + ``projects//locations//builds/``. + """ + + target = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum='OperationType', + ) + request = proto.Field( + proto.MESSAGE, + number=3, + message=any_pb2.Any, + ) + version_id = proto.Field( + proto.INT64, + number=4, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + build_id = proto.Field( + proto.STRING, + number=6, + ) + source_token = proto.Field( + proto.STRING, + number=7, + ) + build_name = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..38940e8 --- /dev/null +++ b/owl-bot-staging/v1/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', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/functions_v1/', + '--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/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py new file mode 100644 index 0000000..f6b67dc --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] +from google.cloud import functions_v1 + + +async def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = await client.call_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py new file mode 100644 index 0000000..7cddbe7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] +from google.cloud import functions_v1 + + +def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = client.call_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py new file mode 100644 index 0000000..dd6b621 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py @@ -0,0 +1,53 @@ +# -*- 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 CreateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] +from google.cloud import functions_v1 + + +async def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py new file mode 100644 index 0000000..117d443 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py @@ -0,0 +1,53 @@ +# -*- 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 CreateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] +from google.cloud import functions_v1 + + +def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py new file mode 100644 index 0000000..3051534 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] +from google.cloud import functions_v1 + + +async def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py new file mode 100644 index 0000000..2262e7b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] +from google.cloud import functions_v1 + + +def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py new file mode 100644 index 0000000..30f6889 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateDownloadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] +from google.cloud import functions_v1 + + +async def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = await client.generate_download_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py new file mode 100644 index 0000000..fbc886f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateDownloadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] +from google.cloud import functions_v1 + + +def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = client.generate_download_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py new file mode 100644 index 0000000..6b19431 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateUploadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] +from google.cloud import functions_v1 + + +async def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = await client.generate_upload_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py new file mode 100644 index 0000000..6e9590a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateUploadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] +from google.cloud import functions_v1 + + +def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = client.generate_upload_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py new file mode 100644 index 0000000..f89b7da --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] +from google.cloud import functions_v1 + + +async def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py new file mode 100644 index 0000000..761c41d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] +from google.cloud import functions_v1 + + +def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = client.get_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py new file mode 100644 index 0000000..09d1b8a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py new file mode 100644 index 0000000..eafe7b7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py new file mode 100644 index 0000000..9a3cd36 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] +from google.cloud import functions_v1 + + +async def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py new file mode 100644 index 0000000..98b3760 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] +from google.cloud import functions_v1 + + +def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py new file mode 100644 index 0000000..2d1128e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py new file mode 100644 index 0000000..b8b14ab --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py new file mode 100644 index 0000000..936744f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py @@ -0,0 +1,47 @@ +# -*- 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py new file mode 100644 index 0000000..c5766f3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py @@ -0,0 +1,47 @@ +# -*- 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py new file mode 100644 index 0000000..4863198 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py @@ -0,0 +1,52 @@ +# -*- 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 UpdateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] +from google.cloud import functions_v1 + + +async def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py new file mode 100644 index 0000000..11809c3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py @@ -0,0 +1,52 @@ +# -*- 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 UpdateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] +from google.cloud import functions_v1 + + +def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json new file mode 100644 index 0000000..9c991cf --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json @@ -0,0 +1,1753 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.functions.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-functions" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.call_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CallFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CallFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "data", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", + "shortName": "call_function" + }, + "description": "Sample for CallFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.call_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CallFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CallFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "data", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", + "shortName": "call_function" + }, + "description": "Sample for CallFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.create_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CreateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CreateFunctionRequest" + }, + { + "name": "location", + "type": "str" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_function" + }, + "description": "Sample for CreateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.create_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CreateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CreateFunctionRequest" + }, + { + "name": "location", + "type": "str" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_function" + }, + "description": "Sample for CreateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.delete_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "DeleteFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_function" + }, + "description": "Sample for DeleteFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.delete_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "DeleteFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_function" + }, + "description": "Sample for DeleteFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_download_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateDownloadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", + "shortName": "generate_download_url" + }, + "description": "Sample for GenerateDownloadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_download_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateDownloadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", + "shortName": "generate_download_url" + }, + "description": "Sample for GenerateDownloadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_upload_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateUploadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", + "shortName": "generate_upload_url" + }, + "description": "Sample for GenerateUploadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_upload_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateUploadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", + "shortName": "generate_upload_url" + }, + "description": "Sample for GenerateUploadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GetFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CloudFunction", + "shortName": "get_function" + }, + "description": "Sample for GetFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GetFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CloudFunction", + "shortName": "get_function" + }, + "description": "Sample for GetFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.list_functions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "ListFunctions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.ListFunctionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager", + "shortName": "list_functions" + }, + "description": "Sample for ListFunctions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.list_functions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "ListFunctions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.ListFunctionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager", + "shortName": "list_functions" + }, + "description": "Sample for ListFunctions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.set_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 43, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 44, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 43, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 44, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.update_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "UpdateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_function" + }, + "description": "Sample for UpdateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.update_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "UpdateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_function" + }, + "description": "Sample for UpdateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py new file mode 100644 index 0000000..6dc057c --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_functions_v1_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 functionsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'call_function': ('name', 'data', ), + 'create_function': ('location', 'function', ), + 'delete_function': ('name', ), + 'generate_download_url': ('name', 'version_id', ), + 'generate_upload_url': ('parent', 'kms_key_name', ), + 'get_function': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'list_functions': ('parent', 'page_size', 'page_token', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_function': ('function', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=functionsCallTransformer(), +): + """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 functions client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..820b19a --- /dev/null +++ b/owl-bot-staging/v1/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-functions', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-functions", + 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] >= 2.8.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.4, < 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/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/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/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/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/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/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/v1/tests/unit/gapic/functions_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__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/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py new file mode 100644 index 0000000..b5d30d9 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py @@ -0,0 +1,3682 @@ +# -*- 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 +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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.functions_v1.services.cloud_functions_service import CloudFunctionsServiceAsyncClient +from google.cloud.functions_v1.services.cloud_functions_service import CloudFunctionsServiceClient +from google.cloud.functions_v1.services.cloud_functions_service import pagers +from google.cloud.functions_v1.services.cloud_functions_service import transports +from google.cloud.functions_v1.types import functions +from google.cloud.functions_v1.types import operations +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 CloudFunctionsServiceClient._get_default_mtls_endpoint(None) is None + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CloudFunctionsServiceClient, "grpc"), + (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CloudFunctionsServiceGrpcTransport, "grpc"), + (transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CloudFunctionsServiceClient, "grpc"), + (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + + +def test_cloud_functions_service_client_get_transport_class(): + transport = CloudFunctionsServiceClient.get_transport_class() + available_transports = [ + transports.CloudFunctionsServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CloudFunctionsServiceClient.get_transport_class("grpc") + assert transport == transports.CloudFunctionsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) +@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) +def test_cloud_functions_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CloudFunctionsServiceClient, '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(CloudFunctionsServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + 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, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "true"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "false"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) +@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_functions_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CloudFunctionsServiceClient, CloudFunctionsServiceAsyncClient +]) +@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) +@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) +def test_cloud_functions_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_cloud_functions_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_cloud_functions_service_client_client_options_from_dict(): + with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CloudFunctionsServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_cloud_functions_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudfunctions.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="cloudfunctions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + functions.ListFunctionsRequest, + dict, +]) +def test_list_functions(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_functions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListFunctionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFunctionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_functions_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 = CloudFunctionsServiceClient( + 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_functions), + '__call__') as call: + client.list_functions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + +@pytest.mark.asyncio +async def test_list_functions_async(transport: str = 'grpc_asyncio', request_type=functions.ListFunctionsRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_functions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFunctionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_functions_async_from_dict(): + await test_list_functions_async(request_type=dict) + + +def test_list_functions_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListFunctionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__') as call: + call.return_value = functions.ListFunctionsResponse() + client.list_functions(request) + + # Establish that the 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_functions_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListFunctionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse()) + await client.list_functions(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_functions_pager(transport_name: str = "grpc"): + client = CloudFunctionsServiceClient( + 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_functions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_functions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, functions.CloudFunction) + for i in results) +def test_list_functions_pages(transport_name: str = "grpc"): + client = CloudFunctionsServiceClient( + 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_functions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + pages = list(client.list_functions(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_functions_async_pager(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_functions(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, functions.CloudFunction) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_functions_async_pages(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_functions(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", [ + functions.GetFunctionRequest, + dict, +]) +def test_get_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CloudFunction( + name='name_value', + description='description_value', + status=functions.CloudFunctionStatus.ACTIVE, + entry_point='entry_point_value', + runtime='runtime_value', + available_memory_mb=1991, + service_account_email='service_account_email_value', + version_id=1074, + network='network_value', + max_instances=1389, + min_instances=1387, + vpc_connector='vpc_connector_value', + vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, + ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, + kms_key_name='kms_key_name_value', + build_worker_pool='build_worker_pool_value', + build_id='build_id_value', + build_name='build_name_value', + source_token='source_token_value', + docker_repository='docker_repository_value', + docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, + source_archive_url='source_archive_url_value', + https_trigger=functions.HttpsTrigger(url='url_value'), + ) + response = client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CloudFunction) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.status == functions.CloudFunctionStatus.ACTIVE + assert response.entry_point == 'entry_point_value' + assert response.runtime == 'runtime_value' + assert response.available_memory_mb == 1991 + assert response.service_account_email == 'service_account_email_value' + assert response.version_id == 1074 + assert response.network == 'network_value' + assert response.max_instances == 1389 + assert response.min_instances == 1387 + assert response.vpc_connector == 'vpc_connector_value' + assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY + assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL + assert response.kms_key_name == 'kms_key_name_value' + assert response.build_worker_pool == 'build_worker_pool_value' + assert response.build_id == 'build_id_value' + assert response.build_name == 'build_name_value' + assert response.source_token == 'source_token_value' + assert response.docker_repository == 'docker_repository_value' + assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY + + +def test_get_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.get_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + +@pytest.mark.asyncio +async def test_get_function_async(transport: str = 'grpc_asyncio', request_type=functions.GetFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction( + name='name_value', + description='description_value', + status=functions.CloudFunctionStatus.ACTIVE, + entry_point='entry_point_value', + runtime='runtime_value', + available_memory_mb=1991, + service_account_email='service_account_email_value', + version_id=1074, + network='network_value', + max_instances=1389, + min_instances=1387, + vpc_connector='vpc_connector_value', + vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, + ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, + kms_key_name='kms_key_name_value', + build_worker_pool='build_worker_pool_value', + build_id='build_id_value', + build_name='build_name_value', + source_token='source_token_value', + docker_repository='docker_repository_value', + docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, + )) + response = await client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CloudFunction) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.status == functions.CloudFunctionStatus.ACTIVE + assert response.entry_point == 'entry_point_value' + assert response.runtime == 'runtime_value' + assert response.available_memory_mb == 1991 + assert response.service_account_email == 'service_account_email_value' + assert response.version_id == 1074 + assert response.network == 'network_value' + assert response.max_instances == 1389 + assert response.min_instances == 1387 + assert response.vpc_connector == 'vpc_connector_value' + assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY + assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL + assert response.kms_key_name == 'kms_key_name_value' + assert response.build_worker_pool == 'build_worker_pool_value' + assert response.build_id == 'build_id_value' + assert response.build_name == 'build_name_value' + assert response.source_token == 'source_token_value' + assert response.docker_repository == 'docker_repository_value' + assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY + + +@pytest.mark.asyncio +async def test_get_function_async_from_dict(): + await test_get_function_async(request_type=dict) + + +def test_get_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GetFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + call.return_value = functions.CloudFunction() + client.get_function(request) + + # Establish that the 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_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GetFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) + await client.get_function(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_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CloudFunction() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_function( + 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_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.GetFunctionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CloudFunction() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_function( + 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_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.GetFunctionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.CreateFunctionRequest, + dict, +]) +def test_create_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.create_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + +@pytest.mark.asyncio +async def test_create_function_async(transport: str = 'grpc_asyncio', request_type=functions.CreateFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_function_async_from_dict(): + await test_create_function_async(request_type=dict) + + +def test_create_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CreateFunctionRequest() + + request.location = 'location_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_function(request) + + # Establish that the 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', + 'location=location_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CreateFunctionRequest() + + request.location = 'location_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_function(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', + 'location=location_value', + ) in kw['metadata'] + + +def test_create_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__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_function( + location='location_value', + function=functions.CloudFunction(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].location + mock_val = 'location_value' + assert arg == mock_val + arg = args[0].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + + +def test_create_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.CreateFunctionRequest(), + location='location_value', + function=functions.CloudFunction(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__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_function( + location='location_value', + function=functions.CloudFunction(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].location + mock_val = 'location_value' + assert arg == mock_val + arg = args[0].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.CreateFunctionRequest(), + location='location_value', + function=functions.CloudFunction(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + functions.UpdateFunctionRequest, + dict, +]) +def test_update_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.update_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + +@pytest.mark.asyncio +async def test_update_function_async(transport: str = 'grpc_asyncio', request_type=functions.UpdateFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_function_async_from_dict(): + await test_update_function_async(request_type=dict) + + +def test_update_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.UpdateFunctionRequest() + + request.function.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_function(request) + + # Establish that the 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', + 'function.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.UpdateFunctionRequest() + + request.function.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_function(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', + 'function.name=name_value', + ) in kw['metadata'] + + +def test_update_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__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_function( + function=functions.CloudFunction(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].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + + +def test_update_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.UpdateFunctionRequest(), + function=functions.CloudFunction(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__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_function( + function=functions.CloudFunction(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].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.UpdateFunctionRequest(), + function=functions.CloudFunction(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + functions.DeleteFunctionRequest, + dict, +]) +def test_delete_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.delete_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + +@pytest.mark.asyncio +async def test_delete_function_async(transport: str = 'grpc_asyncio', request_type=functions.DeleteFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_function_async_from_dict(): + await test_delete_function_async(request_type=dict) + + +def test_delete_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.DeleteFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_function(request) + + # Establish that the 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_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.DeleteFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_function(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_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__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_function( + 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_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.DeleteFunctionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__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_function( + 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_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.DeleteFunctionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.CallFunctionRequest, + dict, +]) +def test_call_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CallFunctionResponse( + execution_id='execution_id_value', + result='result_value', + error='error_value', + ) + response = client.call_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CallFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CallFunctionResponse) + assert response.execution_id == 'execution_id_value' + assert response.result == 'result_value' + assert response.error == 'error_value' + + +def test_call_function_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 = CloudFunctionsServiceClient( + 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.call_function), + '__call__') as call: + client.call_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CallFunctionRequest() + +@pytest.mark.asyncio +async def test_call_function_async(transport: str = 'grpc_asyncio', request_type=functions.CallFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse( + execution_id='execution_id_value', + result='result_value', + error='error_value', + )) + response = await client.call_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CallFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CallFunctionResponse) + assert response.execution_id == 'execution_id_value' + assert response.result == 'result_value' + assert response.error == 'error_value' + + +@pytest.mark.asyncio +async def test_call_function_async_from_dict(): + await test_call_function_async(request_type=dict) + + +def test_call_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CallFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + call.return_value = functions.CallFunctionResponse() + client.call_function(request) + + # Establish that the 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_call_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CallFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) + await client.call_function(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_call_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CallFunctionResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.call_function( + name='name_value', + data='data_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 + arg = args[0].data + mock_val = 'data_value' + assert arg == mock_val + + +def test_call_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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.call_function( + functions.CallFunctionRequest(), + name='name_value', + data='data_value', + ) + +@pytest.mark.asyncio +async def test_call_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CallFunctionResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.call_function( + name='name_value', + data='data_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 + arg = args[0].data + mock_val = 'data_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_call_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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.call_function( + functions.CallFunctionRequest(), + name='name_value', + data='data_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.GenerateUploadUrlRequest, + dict, +]) +def test_generate_upload_url(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.GenerateUploadUrlResponse( + upload_url='upload_url_value', + ) + response = client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateUploadUrlResponse) + assert response.upload_url == 'upload_url_value' + + +def test_generate_upload_url_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 = CloudFunctionsServiceClient( + 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.generate_upload_url), + '__call__') as call: + client.generate_upload_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + +@pytest.mark.asyncio +async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateUploadUrlRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse( + upload_url='upload_url_value', + )) + response = await client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateUploadUrlResponse) + assert response.upload_url == 'upload_url_value' + + +@pytest.mark.asyncio +async def test_generate_upload_url_async_from_dict(): + await test_generate_upload_url_async(request_type=dict) + + +def test_generate_upload_url_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateUploadUrlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + call.return_value = functions.GenerateUploadUrlResponse() + client.generate_upload_url(request) + + # Establish that the 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_generate_upload_url_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateUploadUrlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse()) + await client.generate_upload_url(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'] + + +@pytest.mark.parametrize("request_type", [ + functions.GenerateDownloadUrlRequest, + dict, +]) +def test_generate_download_url(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.GenerateDownloadUrlResponse( + download_url='download_url_value', + ) + response = client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateDownloadUrlResponse) + assert response.download_url == 'download_url_value' + + +def test_generate_download_url_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 = CloudFunctionsServiceClient( + 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.generate_download_url), + '__call__') as call: + client.generate_download_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + +@pytest.mark.asyncio +async def test_generate_download_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateDownloadUrlRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse( + download_url='download_url_value', + )) + response = await client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateDownloadUrlResponse) + assert response.download_url == 'download_url_value' + + +@pytest.mark.asyncio +async def test_generate_download_url_async_from_dict(): + await test_generate_download_url_async(request_type=dict) + + +def test_generate_download_url_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateDownloadUrlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + call.return_value = functions.GenerateDownloadUrlResponse() + client.generate_download_url(request) + + # Establish that the 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_generate_download_url_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateDownloadUrlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse()) + await client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceClient( + 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.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceClient( + 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.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceClient( + 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.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudFunctionsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, +]) +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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudFunctionsServiceGrpcTransport, + ) + +def test_cloud_functions_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudFunctionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_cloud_functions_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CloudFunctionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_functions', + 'get_function', + 'create_function', + 'update_function', + 'delete_function', + 'call_function', + 'generate_upload_url', + 'generate_download_url', + 'set_iam_policy', + 'get_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_cloud_functions_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudFunctionsServiceTransport( + 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_cloud_functions_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudFunctionsServiceTransport() + adc.assert_called_once() + + +def test_cloud_functions_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudFunctionsServiceClient() + 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.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_functions_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, + transports.CloudFunctionsServiceRestTransport, + ], +) +def test_cloud_functions_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudFunctionsServiceGrpcTransport, grpc_helpers), + (transports.CloudFunctionsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_cloud_functions_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "cloudfunctions.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="cloudfunctions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) +def test_cloud_functions_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_cloud_functions_service_host_no_port(transport_name): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_cloud_functions_service_host_with_port(transport_name): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:8000' + ) + +def test_cloud_functions_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudFunctionsServiceGrpcTransport( + 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_cloud_functions_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( + 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.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) +def test_cloud_functions_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) +def test_cloud_functions_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_cloud_functions_service_grpc_lro_client(): + client = CloudFunctionsServiceClient( + 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_cloud_functions_service_grpc_lro_async_client(): + client = CloudFunctionsServiceAsyncClient( + 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_cloud_function_path(): + project = "squid" + location = "clam" + function = "whelk" + expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + actual = CloudFunctionsServiceClient.cloud_function_path(project, location, function) + assert expected == actual + + +def test_parse_cloud_function_path(): + expected = { + "project": "octopus", + "location": "oyster", + "function": "nudibranch", + } + path = CloudFunctionsServiceClient.cloud_function_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_cloud_function_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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_crypto_key_path(path) + assert expected == actual + +def test_repository_path(): + project = "whelk" + location = "octopus" + repository = "oyster" + expected = "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) + actual = CloudFunctionsServiceClient.repository_path(project, location, repository) + assert expected == actual + + +def test_parse_repository_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "repository": "mussel", + } + path = CloudFunctionsServiceClient.repository_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_repository_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CloudFunctionsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = CloudFunctionsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = CloudFunctionsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = CloudFunctionsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CloudFunctionsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = CloudFunctionsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = CloudFunctionsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = CloudFunctionsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CloudFunctionsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = CloudFunctionsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.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.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CloudFunctionsServiceClient.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 = CloudFunctionsServiceAsyncClient( + 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceClient( + 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", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport), +]) +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, + api_audience=None, + ) From 2ecdf8253c572061d36a576010210a564738dffd Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 23 Jun 2022 22:41:49 +0000 Subject: [PATCH 02/16] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-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 --- .../cloud_functions_service/client.py | 1 + .../transports/base.py | 16 +- .../transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/.flake8 | 33 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 -- .../functions_v1/cloud_functions_service.rst | 10 - .../v1/docs/functions_v1/services.rst | 6 - .../v1/docs/functions_v1/types.rst | 7 - owl-bot-staging/v1/docs/index.rst | 7 - .../v1/google/cloud/functions/__init__.py | 67 - .../v1/google/cloud/functions/py.typed | 2 - .../v1/google/cloud/functions_v1/__init__.py | 68 - .../cloud/functions_v1/gapic_metadata.json | 133 - .../v1/google/cloud/functions_v1/py.typed | 2 - .../cloud/functions_v1/services/__init__.py | 15 - .../cloud_functions_service/__init__.py | 22 - .../cloud_functions_service/async_client.py | 1423 ------- .../cloud_functions_service/client.py | 1613 -------- .../cloud_functions_service/pagers.py | 139 - .../transports/__init__.py | 33 - .../transports/base.py | 331 -- .../transports/grpc.py | 593 --- .../transports/grpc_asyncio.py | 592 --- .../cloud/functions_v1/types/__init__.py | 66 - .../cloud/functions_v1/types/functions.py | 1067 ----- .../cloud/functions_v1/types/operations.py | 108 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 180 - ...d_functions_service_call_function_async.py | 46 - ...ud_functions_service_call_function_sync.py | 46 - ...functions_service_create_function_async.py | 53 - ..._functions_service_create_function_sync.py | 53 - ...functions_service_delete_function_async.py | 49 - ..._functions_service_delete_function_sync.py | 49 - ...ons_service_generate_download_url_async.py | 44 - ...ions_service_generate_download_url_sync.py | 44 - ...tions_service_generate_upload_url_async.py | 44 - ...ctions_service_generate_upload_url_sync.py | 44 - ...ud_functions_service_get_function_async.py | 45 - ...oud_functions_service_get_function_sync.py | 45 - ..._functions_service_get_iam_policy_async.py | 46 - ...d_functions_service_get_iam_policy_sync.py | 46 - ..._functions_service_list_functions_async.py | 45 - ...d_functions_service_list_functions_sync.py | 45 - ..._functions_service_set_iam_policy_async.py | 46 - ...d_functions_service_set_iam_policy_sync.py | 46 - ...ions_service_test_iam_permissions_async.py | 47 - ...tions_service_test_iam_permissions_sync.py | 47 - ...functions_service_update_function_async.py | 52 - ..._functions_service_update_function_sync.py | 52 - .../snippet_metadata_functions_v1.json | 1753 -------- .../v1/scripts/fixup_functions_v1_keywords.py | 186 - owl-bot-staging/v1/setup.py | 60 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/functions_v1/__init__.py | 16 - .../test_cloud_functions_service.py | 3682 ----------------- .../test_cloud_functions_service.py | 53 + 63 files changed, 69 insertions(+), 13748 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/.flake8 delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst delete mode 100644 owl-bot-staging/v1/docs/functions_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/functions_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/google/cloud/functions/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json delete mode 100644 owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py diff --git a/google/cloud/functions_v1/services/cloud_functions_service/client.py b/google/cloud/functions_v1/services/cloud_functions_service/client.py index 7e28192..62c6d5f 100644 --- a/google/cloud/functions_v1/services/cloud_functions_service/client.py +++ b/google/cloud/functions_v1/services/cloud_functions_service/client.py @@ -483,6 +483,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def list_functions( diff --git a/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py b/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py index 7d8f267..43ebae9 100644 --- a/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py +++ b/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py @@ -57,6 +57,7 @@ def __init__( quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -84,11 +85,6 @@ def __init__( 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. @@ -109,6 +105,11 @@ def __init__( credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. if ( @@ -121,6 +122,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py b/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py index 787b6e7..777cbcb 100644 --- a/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py +++ b/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. @@ -157,6 +158,7 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: diff --git a/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py b/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py index 96fdade..818f79d 100644 --- a/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py +++ b/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py @@ -106,6 +106,7 @@ def __init__( quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. @@ -202,6 +203,7 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index ca93bdf..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/functions/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 deleted file mode 100644 index 29227d4..0000000 --- a/owl-bot-staging/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 9e8399a..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/functions *.py -recursive-include google/cloud/functions_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 533650a..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Functions 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 Functions API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 3464a12..0000000 --- a/owl-bot-staging/v1/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-functions 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-functions" -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-functions-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-functions.tex", - u"google-cloud-functions 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-functions", - u"Google Cloud Functions 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-functions", - u"google-cloud-functions Documentation", - author, - "google-cloud-functions", - "GAPIC library for Google Cloud Functions API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst b/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst deleted file mode 100644 index 36d0114..0000000 --- a/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CloudFunctionsService ---------------------------------------- - -.. automodule:: google.cloud.functions_v1.services.cloud_functions_service - :members: - :inherited-members: - -.. automodule:: google.cloud.functions_v1.services.cloud_functions_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/functions_v1/services.rst b/owl-bot-staging/v1/docs/functions_v1/services.rst deleted file mode 100644 index 89ae970..0000000 --- a/owl-bot-staging/v1/docs/functions_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Functions v1 API -========================================== -.. toctree:: - :maxdepth: 2 - - cloud_functions_service diff --git a/owl-bot-staging/v1/docs/functions_v1/types.rst b/owl-bot-staging/v1/docs/functions_v1/types.rst deleted file mode 100644 index bebdfe9..0000000 --- a/owl-bot-staging/v1/docs/functions_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Functions v1 API -======================================= - -.. automodule:: google.cloud.functions_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index dc30f6d..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - functions_v1/services - functions_v1/types diff --git a/owl-bot-staging/v1/google/cloud/functions/__init__.py b/owl-bot-staging/v1/google/cloud/functions/__init__.py deleted file mode 100644 index c34f3b0..0000000 --- a/owl-bot-staging/v1/google/cloud/functions/__init__.py +++ /dev/null @@ -1,67 +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.functions_v1.services.cloud_functions_service.client import CloudFunctionsServiceClient -from google.cloud.functions_v1.services.cloud_functions_service.async_client import CloudFunctionsServiceAsyncClient - -from google.cloud.functions_v1.types.functions import CallFunctionRequest -from google.cloud.functions_v1.types.functions import CallFunctionResponse -from google.cloud.functions_v1.types.functions import CloudFunction -from google.cloud.functions_v1.types.functions import CreateFunctionRequest -from google.cloud.functions_v1.types.functions import DeleteFunctionRequest -from google.cloud.functions_v1.types.functions import EventTrigger -from google.cloud.functions_v1.types.functions import FailurePolicy -from google.cloud.functions_v1.types.functions import GenerateDownloadUrlRequest -from google.cloud.functions_v1.types.functions import GenerateDownloadUrlResponse -from google.cloud.functions_v1.types.functions import GenerateUploadUrlRequest -from google.cloud.functions_v1.types.functions import GenerateUploadUrlResponse -from google.cloud.functions_v1.types.functions import GetFunctionRequest -from google.cloud.functions_v1.types.functions import HttpsTrigger -from google.cloud.functions_v1.types.functions import ListFunctionsRequest -from google.cloud.functions_v1.types.functions import ListFunctionsResponse -from google.cloud.functions_v1.types.functions import SecretEnvVar -from google.cloud.functions_v1.types.functions import SecretVolume -from google.cloud.functions_v1.types.functions import SourceRepository -from google.cloud.functions_v1.types.functions import UpdateFunctionRequest -from google.cloud.functions_v1.types.functions import CloudFunctionStatus -from google.cloud.functions_v1.types.operations import OperationMetadataV1 -from google.cloud.functions_v1.types.operations import OperationType - -__all__ = ('CloudFunctionsServiceClient', - 'CloudFunctionsServiceAsyncClient', - 'CallFunctionRequest', - 'CallFunctionResponse', - 'CloudFunction', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventTrigger', - 'FailurePolicy', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'HttpsTrigger', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'SecretEnvVar', - 'SecretVolume', - 'SourceRepository', - 'UpdateFunctionRequest', - 'CloudFunctionStatus', - 'OperationMetadataV1', - 'OperationType', -) diff --git a/owl-bot-staging/v1/google/cloud/functions/py.typed b/owl-bot-staging/v1/google/cloud/functions/py.typed deleted file mode 100644 index 982ebb1..0000000 --- a/owl-bot-staging/v1/google/cloud/functions/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py deleted file mode 100644 index 87351c6..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py +++ /dev/null @@ -1,68 +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.cloud_functions_service import CloudFunctionsServiceClient -from .services.cloud_functions_service import CloudFunctionsServiceAsyncClient - -from .types.functions import CallFunctionRequest -from .types.functions import CallFunctionResponse -from .types.functions import CloudFunction -from .types.functions import CreateFunctionRequest -from .types.functions import DeleteFunctionRequest -from .types.functions import EventTrigger -from .types.functions import FailurePolicy -from .types.functions import GenerateDownloadUrlRequest -from .types.functions import GenerateDownloadUrlResponse -from .types.functions import GenerateUploadUrlRequest -from .types.functions import GenerateUploadUrlResponse -from .types.functions import GetFunctionRequest -from .types.functions import HttpsTrigger -from .types.functions import ListFunctionsRequest -from .types.functions import ListFunctionsResponse -from .types.functions import SecretEnvVar -from .types.functions import SecretVolume -from .types.functions import SourceRepository -from .types.functions import UpdateFunctionRequest -from .types.functions import CloudFunctionStatus -from .types.operations import OperationMetadataV1 -from .types.operations import OperationType - -__all__ = ( - 'CloudFunctionsServiceAsyncClient', -'CallFunctionRequest', -'CallFunctionResponse', -'CloudFunction', -'CloudFunctionStatus', -'CloudFunctionsServiceClient', -'CreateFunctionRequest', -'DeleteFunctionRequest', -'EventTrigger', -'FailurePolicy', -'GenerateDownloadUrlRequest', -'GenerateDownloadUrlResponse', -'GenerateUploadUrlRequest', -'GenerateUploadUrlResponse', -'GetFunctionRequest', -'HttpsTrigger', -'ListFunctionsRequest', -'ListFunctionsResponse', -'OperationMetadataV1', -'OperationType', -'SecretEnvVar', -'SecretVolume', -'SourceRepository', -'UpdateFunctionRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json deleted file mode 100644 index 5745d05..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json +++ /dev/null @@ -1,133 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.functions_v1", - "protoPackage": "google.cloud.functions.v1", - "schema": "1.0", - "services": { - "CloudFunctionsService": { - "clients": { - "grpc": { - "libraryClient": "CloudFunctionsServiceClient", - "rpcs": { - "CallFunction": { - "methods": [ - "call_function" - ] - }, - "CreateFunction": { - "methods": [ - "create_function" - ] - }, - "DeleteFunction": { - "methods": [ - "delete_function" - ] - }, - "GenerateDownloadUrl": { - "methods": [ - "generate_download_url" - ] - }, - "GenerateUploadUrl": { - "methods": [ - "generate_upload_url" - ] - }, - "GetFunction": { - "methods": [ - "get_function" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFunctions": { - "methods": [ - "list_functions" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFunction": { - "methods": [ - "update_function" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CloudFunctionsServiceAsyncClient", - "rpcs": { - "CallFunction": { - "methods": [ - "call_function" - ] - }, - "CreateFunction": { - "methods": [ - "create_function" - ] - }, - "DeleteFunction": { - "methods": [ - "delete_function" - ] - }, - "GenerateDownloadUrl": { - "methods": [ - "generate_download_url" - ] - }, - "GenerateUploadUrl": { - "methods": [ - "generate_upload_url" - ] - }, - "GetFunction": { - "methods": [ - "get_function" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFunctions": { - "methods": [ - "list_functions" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFunction": { - "methods": [ - "update_function" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/py.typed b/owl-bot-staging/v1/google/cloud/functions_v1/py.typed deleted file mode 100644 index 982ebb1..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py deleted file mode 100644 index e8e1c38..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/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/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py deleted file mode 100644 index d784dc7..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__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 CloudFunctionsServiceClient -from .async_client import CloudFunctionsServiceAsyncClient - -__all__ = ( - 'CloudFunctionsServiceClient', - 'CloudFunctionsServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py deleted file mode 100644 index 3010041..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py +++ /dev/null @@ -1,1423 +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_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport -from .client import CloudFunctionsServiceClient - - -class CloudFunctionsServiceAsyncClient: - """A service that application uses to manipulate triggers and - functions. - """ - - _client: CloudFunctionsServiceClient - - DEFAULT_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT - - cloud_function_path = staticmethod(CloudFunctionsServiceClient.cloud_function_path) - parse_cloud_function_path = staticmethod(CloudFunctionsServiceClient.parse_cloud_function_path) - crypto_key_path = staticmethod(CloudFunctionsServiceClient.crypto_key_path) - parse_crypto_key_path = staticmethod(CloudFunctionsServiceClient.parse_crypto_key_path) - repository_path = staticmethod(CloudFunctionsServiceClient.repository_path) - parse_repository_path = staticmethod(CloudFunctionsServiceClient.parse_repository_path) - common_billing_account_path = staticmethod(CloudFunctionsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CloudFunctionsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CloudFunctionsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CloudFunctionsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CloudFunctionsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CloudFunctionsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CloudFunctionsServiceClient.common_project_path) - parse_common_project_path = staticmethod(CloudFunctionsServiceClient.parse_common_project_path) - common_location_path = staticmethod(CloudFunctionsServiceClient.common_location_path) - parse_common_location_path = staticmethod(CloudFunctionsServiceClient.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: - CloudFunctionsServiceAsyncClient: The constructed client. - """ - return CloudFunctionsServiceClient.from_service_account_info.__func__(CloudFunctionsServiceAsyncClient, 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: - CloudFunctionsServiceAsyncClient: The constructed client. - """ - return CloudFunctionsServiceClient.from_service_account_file.__func__(CloudFunctionsServiceAsyncClient, 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 CloudFunctionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CloudFunctionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CloudFunctionsServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CloudFunctionsServiceClient).get_transport_class, type(CloudFunctionsServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CloudFunctionsServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the cloud functions service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CloudFunctionsServiceTransport]): 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 = CloudFunctionsServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_functions(self, - request: Union[functions.ListFunctionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsAsyncPager: - r"""Returns a list of functions that belong to the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): - The request object. Request for the `ListFunctions` - 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager: - Response for the ListFunctions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = functions.ListFunctionsRequest(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.list_functions, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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.ListFunctionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_function(self, - request: Union[functions.GetFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CloudFunction: - r"""Returns a function with the given name from the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): - The request object. Request for the `GetFunction` - method. - name (:class:`str`): - Required. The name of the function - which details should be obtained. - - 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.functions_v1.types.CloudFunction: - Describes a Cloud Function that - contains user computation executed in - response to an event. It encapsulate - function and triggers configurations. - - """ - # 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 = functions.GetFunctionRequest(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_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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 create_function(self, - request: Union[functions.CreateFunctionRequest, dict] = None, - *, - location: str = None, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): - The request object. Request for the `CreateFunction` - method. - location (:class:`str`): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - function (:class:`google.cloud.functions_v1.types.CloudFunction`): - Required. Function to be created. - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([location, function]) - if request is 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 = functions.CreateFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if function is not None: - request.function = function - - # 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_function, - default_timeout=600.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(( - ("location", request.location), - )), - ) - - # 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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def update_function(self, - request: Union[functions.UpdateFunctionRequest, dict] = None, - *, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates existing function. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): - The request object. Request for the `UpdateFunction` - method. - function (:class:`google.cloud.functions_v1.types.CloudFunction`): - Required. New version of the - function. - - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([function]) - if request is 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 = functions.UpdateFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if function is not None: - request.function = function - - # 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_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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(( - ("function.name", request.function.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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def delete_function(self, - request: Union[functions.DeleteFunctionRequest, 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 function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): - The request object. Request for the `DeleteFunction` - method. - name (:class:`str`): - Required. The name of the function - which should be deleted. - - 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.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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 = functions.DeleteFunctionRequest(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_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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, - empty_pb2.Empty, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def call_function(self, - request: Union[functions.CallFunctionRequest, dict] = None, - *, - name: str = None, - data: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CallFunctionResponse: - r"""Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = await client.call_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): - The request object. Request for the `CallFunction` - method. - name (:class:`str`): - Required. The name of the function to - be called. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (:class:`str`): - Required. Input to be passed to the - function. - - This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: - Response of CallFunction method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, data]) - if request is 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 = functions.CallFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.call_function, - default_timeout=600.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 generate_upload_url(self, - request: Union[functions.GenerateUploadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateUploadUrlResponse: - r"""Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = await client.generate_upload_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): - The request object. Request of `GenerateSourceUploadUrl` - 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.cloud.functions_v1.types.GenerateUploadUrlResponse: - Response of GenerateSourceUploadUrl method. - """ - # Create or coerce a protobuf request object. - request = functions.GenerateUploadUrlRequest(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.generate_upload_url, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def generate_download_url(self, - request: Union[functions.GenerateDownloadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateDownloadUrlResponse: - r"""Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = await client.generate_download_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): - The request object. Request of `GenerateDownloadUrl` - 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: - Response of GenerateDownloadUrl method. - """ - # Create or coerce a protobuf request object. - request = functions.GenerateDownloadUrlRequest(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.generate_download_url, - 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 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 on the specified - function. Replaces any existing policy. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await 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 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"""Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await 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 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"""Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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) - - 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-functions", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CloudFunctionsServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py deleted file mode 100644 index 53c6f1a..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py +++ /dev/null @@ -1,1613 +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_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CloudFunctionsServiceGrpcTransport -from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport - - -class CloudFunctionsServiceClientMeta(type): - """Metaclass for the CloudFunctionsService 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[CloudFunctionsServiceTransport]] - _transport_registry["grpc"] = CloudFunctionsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CloudFunctionsServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CloudFunctionsServiceTransport]: - """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 CloudFunctionsServiceClient(metaclass=CloudFunctionsServiceClientMeta): - """A service that application uses to manipulate triggers and - functions. - """ - - @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 = "cloudfunctions.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: - CloudFunctionsServiceClient: 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: - CloudFunctionsServiceClient: 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) -> CloudFunctionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CloudFunctionsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def cloud_function_path(project: str,location: str,function: str,) -> str: - """Returns a fully-qualified cloud_function string.""" - return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) - - @staticmethod - def parse_cloud_function_path(path: str) -> Dict[str,str]: - """Parses a cloud_function path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?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 repository_path(project: str,location: str,repository: str,) -> str: - """Returns a fully-qualified repository string.""" - return "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) - - @staticmethod - def parse_repository_path(path: str) -> Dict[str,str]: - """Parses a repository path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/repositories/(?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, CloudFunctionsServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the cloud functions service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CloudFunctionsServiceTransport]): 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, CloudFunctionsServiceTransport): - # transport is a CloudFunctionsServiceTransport 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, - api_audience=client_options.api_audience, - ) - - def list_functions(self, - request: Union[functions.ListFunctionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsPager: - r"""Returns a list of functions that belong to the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): - The request object. Request for the `ListFunctions` - 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager: - Response for the ListFunctions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a functions.ListFunctionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.ListFunctionsRequest): - request = functions.ListFunctionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_functions] - - # 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.ListFunctionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_function(self, - request: Union[functions.GetFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CloudFunction: - r"""Returns a function with the given name from the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = client.get_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): - The request object. Request for the `GetFunction` - method. - name (str): - Required. The name of the function - which details should be obtained. - - 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.functions_v1.types.CloudFunction: - Describes a Cloud Function that - contains user computation executed in - response to an event. It encapsulate - function and triggers configurations. - - """ - # 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 functions.GetFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.GetFunctionRequest): - request = functions.GetFunctionRequest(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_function] - - # 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 create_function(self, - request: Union[functions.CreateFunctionRequest, dict] = None, - *, - location: str = None, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): - The request object. Request for the `CreateFunction` - method. - location (str): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - function (google.cloud.functions_v1.types.CloudFunction): - Required. Function to be created. - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([location, function]) - if request is 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 functions.CreateFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.CreateFunctionRequest): - request = functions.CreateFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if function is not None: - request.function = function - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_function] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("location", request.location), - )), - ) - - # 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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def update_function(self, - request: Union[functions.UpdateFunctionRequest, dict] = None, - *, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates existing function. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): - The request object. Request for the `UpdateFunction` - method. - function (google.cloud.functions_v1.types.CloudFunction): - Required. New version of the - function. - - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([function]) - if request is 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 functions.UpdateFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.UpdateFunctionRequest): - request = functions.UpdateFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if function is not None: - request.function = function - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_function] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("function.name", request.function.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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def delete_function(self, - request: Union[functions.DeleteFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): - The request object. Request for the `DeleteFunction` - method. - name (str): - Required. The name of the function - which should be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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 functions.DeleteFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.DeleteFunctionRequest): - request = functions.DeleteFunctionRequest(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_function] - - # 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, - empty_pb2.Empty, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def call_function(self, - request: Union[functions.CallFunctionRequest, dict] = None, - *, - name: str = None, - data: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CallFunctionResponse: - r"""Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = client.call_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): - The request object. Request for the `CallFunction` - method. - name (str): - Required. The name of the function to - be called. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (str): - Required. Input to be passed to the - function. - - This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: - Response of CallFunction method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, data]) - if request is 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 functions.CallFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.CallFunctionRequest): - request = functions.CallFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.call_function] - - # 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 generate_upload_url(self, - request: Union[functions.GenerateUploadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateUploadUrlResponse: - r"""Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = client.generate_upload_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): - The request object. Request of `GenerateSourceUploadUrl` - 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.cloud.functions_v1.types.GenerateUploadUrlResponse: - Response of GenerateSourceUploadUrl method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a functions.GenerateUploadUrlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.GenerateUploadUrlRequest): - request = functions.GenerateUploadUrlRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_upload_url] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_download_url(self, - request: Union[functions.GenerateDownloadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateDownloadUrlResponse: - r"""Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = client.generate_download_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): - The request object. Request of `GenerateDownloadUrl` - 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: - Response of GenerateDownloadUrl method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a functions.GenerateDownloadUrlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.GenerateDownloadUrlRequest): - request = functions.GenerateDownloadUrlRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_download_url] - - # 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 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 on the specified - function. Replaces any existing policy. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 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"""Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 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"""Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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-functions", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CloudFunctionsServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py deleted file mode 100644 index f31d4f1..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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.functions_v1.types import functions - - -class ListFunctionsPager: - """A pager for iterating through ``list_functions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``functions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFunctions`` requests and continue to iterate - through the ``functions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` - 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[..., functions.ListFunctionsResponse], - request: functions.ListFunctionsRequest, - response: functions.ListFunctionsResponse, - *, - 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.functions_v1.types.ListFunctionsRequest): - The initial request object. - response (google.cloud.functions_v1.types.ListFunctionsResponse): - 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 = functions.ListFunctionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[functions.ListFunctionsResponse]: - 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[functions.CloudFunction]: - for page in self.pages: - yield from page.functions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFunctionsAsyncPager: - """A pager for iterating through ``list_functions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``functions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFunctions`` requests and continue to iterate - through the ``functions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` - 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[functions.ListFunctionsResponse]], - request: functions.ListFunctionsRequest, - response: functions.ListFunctionsResponse, - *, - 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.functions_v1.types.ListFunctionsRequest): - The initial request object. - response (google.cloud.functions_v1.types.ListFunctionsResponse): - 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 = functions.ListFunctionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[functions.ListFunctionsResponse]: - 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[functions.CloudFunction]: - async def async_generator(): - async for page in self.pages: - for response in page.functions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py deleted file mode 100644 index ac1ba7e..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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 CloudFunctionsServiceTransport -from .grpc import CloudFunctionsServiceGrpcTransport -from .grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CloudFunctionsServiceTransport]] -_transport_registry['grpc'] = CloudFunctionsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CloudFunctionsServiceGrpcAsyncIOTransport - -__all__ = ( - 'CloudFunctionsServiceTransport', - 'CloudFunctionsServiceGrpcTransport', - 'CloudFunctionsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py deleted file mode 100644 index 2d3352f..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py +++ /dev/null @@ -1,331 +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.functions_v1.types import functions -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-functions', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CloudFunctionsServiceTransport(abc.ABC): - """Abstract transport class for CloudFunctionsService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'cloudfunctions.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, - api_audience: Optional[str] = None, - **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. - """ - - 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) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_functions: gapic_v1.method.wrap_method( - self.list_functions, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_function: gapic_v1.method.wrap_method( - self.get_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.create_function: gapic_v1.method.wrap_method( - self.create_function, - default_timeout=600.0, - client_info=client_info, - ), - self.update_function: gapic_v1.method.wrap_method( - self.update_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.delete_function: gapic_v1.method.wrap_method( - self.delete_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.call_function: gapic_v1.method.wrap_method( - self.call_function, - default_timeout=600.0, - client_info=client_info, - ), - self.generate_upload_url: gapic_v1.method.wrap_method( - self.generate_upload_url, - default_timeout=None, - client_info=client_info, - ), - self.generate_download_url: gapic_v1.method.wrap_method( - self.generate_download_url, - 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.get_iam_policy: gapic_v1.method.wrap_method( - self.get_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 list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - Union[ - functions.ListFunctionsResponse, - Awaitable[functions.ListFunctionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - Union[ - functions.CloudFunction, - Awaitable[functions.CloudFunction] - ]]: - raise NotImplementedError() - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - Union[ - functions.CallFunctionResponse, - Awaitable[functions.CallFunctionResponse] - ]]: - raise NotImplementedError() - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - Union[ - functions.GenerateUploadUrlResponse, - Awaitable[functions.GenerateUploadUrlResponse] - ]]: - raise NotImplementedError() - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - Union[ - functions.GenerateDownloadUrlResponse, - Awaitable[functions.GenerateDownloadUrlResponse] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CloudFunctionsServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py deleted file mode 100644 index 92c02c9..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py +++ /dev/null @@ -1,593 +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.functions_v1.types import functions -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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO - - -class CloudFunctionsServiceGrpcTransport(CloudFunctionsServiceTransport): - """gRPC backend transport for CloudFunctionsService. - - A service that application uses to manipulate triggers and - functions. - - 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 = 'cloudfunctions.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, - api_audience: Optional[str] = None, - ) -> 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, - api_audience=api_audience, - ) - - 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 = 'cloudfunctions.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 list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - functions.ListFunctionsResponse]: - r"""Return a callable for the list functions method over gRPC. - - Returns a list of functions that belong to the - requested project. - - Returns: - Callable[[~.ListFunctionsRequest], - ~.ListFunctionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_functions' not in self._stubs: - self._stubs['list_functions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', - request_serializer=functions.ListFunctionsRequest.serialize, - response_deserializer=functions.ListFunctionsResponse.deserialize, - ) - return self._stubs['list_functions'] - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - functions.CloudFunction]: - r"""Return a callable for the get function method over gRPC. - - Returns a function with the given name from the - requested project. - - Returns: - Callable[[~.GetFunctionRequest], - ~.CloudFunction]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_function' not in self._stubs: - self._stubs['get_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', - request_serializer=functions.GetFunctionRequest.serialize, - response_deserializer=functions.CloudFunction.deserialize, - ) - return self._stubs['get_function'] - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create function method over gRPC. - - Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - Returns: - Callable[[~.CreateFunctionRequest], - ~.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_function' not in self._stubs: - self._stubs['create_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', - request_serializer=functions.CreateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_function'] - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - operations_pb2.Operation]: - r"""Return a callable for the update function method over gRPC. - - Updates existing function. - - Returns: - Callable[[~.UpdateFunctionRequest], - ~.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_function' not in self._stubs: - self._stubs['update_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', - request_serializer=functions.UpdateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_function'] - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete function method over gRPC. - - Deletes a function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - Returns: - Callable[[~.DeleteFunctionRequest], - ~.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_function' not in self._stubs: - self._stubs['delete_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', - request_serializer=functions.DeleteFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_function'] - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - functions.CallFunctionResponse]: - r"""Return a callable for the call function method over gRPC. - - Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - Returns: - Callable[[~.CallFunctionRequest], - ~.CallFunctionResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'call_function' not in self._stubs: - self._stubs['call_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', - request_serializer=functions.CallFunctionRequest.serialize, - response_deserializer=functions.CallFunctionResponse.deserialize, - ) - return self._stubs['call_function'] - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - functions.GenerateUploadUrlResponse]: - r"""Return a callable for the generate upload url method over gRPC. - - Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - Returns: - Callable[[~.GenerateUploadUrlRequest], - ~.GenerateUploadUrlResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_upload_url' not in self._stubs: - self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', - request_serializer=functions.GenerateUploadUrlRequest.serialize, - response_deserializer=functions.GenerateUploadUrlResponse.deserialize, - ) - return self._stubs['generate_upload_url'] - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - functions.GenerateDownloadUrlResponse]: - r"""Return a callable for the generate download url method over gRPC. - - Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - Returns: - Callable[[~.GenerateDownloadUrlRequest], - ~.GenerateDownloadUrlResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_download_url' not in self._stubs: - self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', - request_serializer=functions.GenerateDownloadUrlRequest.serialize, - response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, - ) - return self._stubs['generate_download_url'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - r"""Return a callable for the test iam permissions method over gRPC. - - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/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__ = ( - 'CloudFunctionsServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py deleted file mode 100644 index d05047d..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,592 +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.functions_v1.types import functions -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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CloudFunctionsServiceGrpcTransport - - -class CloudFunctionsServiceGrpcAsyncIOTransport(CloudFunctionsServiceTransport): - """gRPC AsyncIO backend transport for CloudFunctionsService. - - A service that application uses to manipulate triggers and - functions. - - 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 = 'cloudfunctions.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 = 'cloudfunctions.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, - api_audience: Optional[str] = None, - ) -> 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, - api_audience=api_audience, - ) - - 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 list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - Awaitable[functions.ListFunctionsResponse]]: - r"""Return a callable for the list functions method over gRPC. - - Returns a list of functions that belong to the - requested project. - - Returns: - Callable[[~.ListFunctionsRequest], - Awaitable[~.ListFunctionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_functions' not in self._stubs: - self._stubs['list_functions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', - request_serializer=functions.ListFunctionsRequest.serialize, - response_deserializer=functions.ListFunctionsResponse.deserialize, - ) - return self._stubs['list_functions'] - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - Awaitable[functions.CloudFunction]]: - r"""Return a callable for the get function method over gRPC. - - Returns a function with the given name from the - requested project. - - Returns: - Callable[[~.GetFunctionRequest], - Awaitable[~.CloudFunction]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_function' not in self._stubs: - self._stubs['get_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', - request_serializer=functions.GetFunctionRequest.serialize, - response_deserializer=functions.CloudFunction.deserialize, - ) - return self._stubs['get_function'] - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create function method over gRPC. - - Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - Returns: - Callable[[~.CreateFunctionRequest], - 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_function' not in self._stubs: - self._stubs['create_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', - request_serializer=functions.CreateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_function'] - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update function method over gRPC. - - Updates existing function. - - Returns: - Callable[[~.UpdateFunctionRequest], - 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_function' not in self._stubs: - self._stubs['update_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', - request_serializer=functions.UpdateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_function'] - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete function method over gRPC. - - Deletes a function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - Returns: - Callable[[~.DeleteFunctionRequest], - 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_function' not in self._stubs: - self._stubs['delete_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', - request_serializer=functions.DeleteFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_function'] - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - Awaitable[functions.CallFunctionResponse]]: - r"""Return a callable for the call function method over gRPC. - - Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - Returns: - Callable[[~.CallFunctionRequest], - Awaitable[~.CallFunctionResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'call_function' not in self._stubs: - self._stubs['call_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', - request_serializer=functions.CallFunctionRequest.serialize, - response_deserializer=functions.CallFunctionResponse.deserialize, - ) - return self._stubs['call_function'] - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - Awaitable[functions.GenerateUploadUrlResponse]]: - r"""Return a callable for the generate upload url method over gRPC. - - Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - Returns: - Callable[[~.GenerateUploadUrlRequest], - Awaitable[~.GenerateUploadUrlResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_upload_url' not in self._stubs: - self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', - request_serializer=functions.GenerateUploadUrlRequest.serialize, - response_deserializer=functions.GenerateUploadUrlResponse.deserialize, - ) - return self._stubs['generate_upload_url'] - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - Awaitable[functions.GenerateDownloadUrlResponse]]: - r"""Return a callable for the generate download url method over gRPC. - - Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - Returns: - Callable[[~.GenerateDownloadUrlRequest], - Awaitable[~.GenerateDownloadUrlResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_download_url' not in self._stubs: - self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', - request_serializer=functions.GenerateDownloadUrlRequest.serialize, - response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, - ) - return self._stubs['generate_download_url'] - - @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 on the specified - function. Replaces 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.functions.v1.CloudFunctionsService/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - Returns: - Callable[[~.GetIamPolicyRequest], - 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.functions.v1.CloudFunctionsService/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Returns: - Callable[[~.TestIamPermissionsRequest], - 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.functions.v1.CloudFunctionsService/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__ = ( - 'CloudFunctionsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py deleted file mode 100644 index b09e206..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py +++ /dev/null @@ -1,66 +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 .functions import ( - CallFunctionRequest, - CallFunctionResponse, - CloudFunction, - CreateFunctionRequest, - DeleteFunctionRequest, - EventTrigger, - FailurePolicy, - GenerateDownloadUrlRequest, - GenerateDownloadUrlResponse, - GenerateUploadUrlRequest, - GenerateUploadUrlResponse, - GetFunctionRequest, - HttpsTrigger, - ListFunctionsRequest, - ListFunctionsResponse, - SecretEnvVar, - SecretVolume, - SourceRepository, - UpdateFunctionRequest, - CloudFunctionStatus, -) -from .operations import ( - OperationMetadataV1, - OperationType, -) - -__all__ = ( - 'CallFunctionRequest', - 'CallFunctionResponse', - 'CloudFunction', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventTrigger', - 'FailurePolicy', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'HttpsTrigger', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'SecretEnvVar', - 'SecretVolume', - 'SourceRepository', - 'UpdateFunctionRequest', - 'CloudFunctionStatus', - 'OperationMetadataV1', - 'OperationType', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py deleted file mode 100644 index 844c961..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py +++ /dev/null @@ -1,1067 +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 duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.functions.v1', - manifest={ - 'CloudFunctionStatus', - 'CloudFunction', - 'SourceRepository', - 'HttpsTrigger', - 'EventTrigger', - 'FailurePolicy', - 'SecretEnvVar', - 'SecretVolume', - 'CreateFunctionRequest', - 'UpdateFunctionRequest', - 'GetFunctionRequest', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'DeleteFunctionRequest', - 'CallFunctionRequest', - 'CallFunctionResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - }, -) - - -class CloudFunctionStatus(proto.Enum): - r"""Describes the current stage of a deployment.""" - CLOUD_FUNCTION_STATUS_UNSPECIFIED = 0 - ACTIVE = 1 - OFFLINE = 2 - DEPLOY_IN_PROGRESS = 3 - DELETE_IN_PROGRESS = 4 - UNKNOWN = 5 - - -class CloudFunction(proto.Message): - r"""Describes a Cloud Function that contains user computation - executed in response to an event. It encapsulate function and - triggers configurations. - - 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): - A user-defined name of the function. Function names must be - unique globally and match pattern - ``projects/*/locations/*/functions/*`` - description (str): - User-provided description of a function. - source_archive_url (str): - The Google Cloud Storage URL, starting with ``gs://``, - pointing to the zip archive which contains the function. - - This field is a member of `oneof`_ ``source_code``. - source_repository (google.cloud.functions_v1.types.SourceRepository): - **Beta Feature** - - The source repository where a function is hosted. - - This field is a member of `oneof`_ ``source_code``. - source_upload_url (str): - The Google Cloud Storage signed URL used for source - uploading, generated by calling - [google.cloud.functions.v1.GenerateUploadUrl]. - - The signature is validated on write methods (Create, Update) - The signature is stripped from the Function object on read - methods (Get, List) - - This field is a member of `oneof`_ ``source_code``. - https_trigger (google.cloud.functions_v1.types.HttpsTrigger): - An HTTPS endpoint type of source that can be - triggered via URL. - - This field is a member of `oneof`_ ``trigger``. - event_trigger (google.cloud.functions_v1.types.EventTrigger): - A source that fires events in response to a - condition in another service. - - This field is a member of `oneof`_ ``trigger``. - status (google.cloud.functions_v1.types.CloudFunctionStatus): - Output only. Status of the function - deployment. - entry_point (str): - The name of the function (as defined in source code) that - will be executed. Defaults to the resource name suffix, if - not specified. For backward compatibility, if function with - given name is not found, then the system will try to use - function named "function". For Node.js this is name of a - function exported by the module specified in - ``source_location``. - runtime (str): - The runtime in which to run the function. Required when - deploying a new function, optional when updating an existing - function. For a complete list of possible choices, see the - ```gcloud`` command - reference `__. - timeout (google.protobuf.duration_pb2.Duration): - The function execution timeout. Execution is - considered failed and can be terminated if the - function is not completed at the end of the - timeout period. Defaults to 60 seconds. - available_memory_mb (int): - The amount of memory in MB available for a - function. Defaults to 256MB. - service_account_email (str): - The email of the function's service account. If empty, - defaults to ``{project_id}@appspot.gserviceaccount.com``. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last update timestamp of a - Cloud Function. - version_id (int): - Output only. The version identifier of the - Cloud Function. Each deployment attempt results - in a new version of a function being created. - labels (Mapping[str, str]): - Labels associated with this Cloud Function. - environment_variables (Mapping[str, str]): - Environment variables that shall be available - during function execution. - build_environment_variables (Mapping[str, str]): - Build environment variables that shall be - available during build time. - network (str): - The VPC Network that this cloud function can connect to. It - can be either the fully-qualified URI, or the short name of - the network resource. If the short network name is used, the - network must belong to the same project. Otherwise, it must - belong to a project within the same organization. The format - of this field is either - ``projects/{project}/global/networks/{network}`` or - ``{network}``, where ``{project}`` is a project id where the - network is defined, and ``{network}`` is the short name of - the network. - - This field is mutually exclusive with ``vpc_connector`` and - will be replaced by it. - - See `the VPC - documentation `__ - for more information on connecting Cloud projects. - max_instances (int): - The limit on the maximum number of function instances that - may coexist at a given time. - - In some cases, such as rapid traffic surges, Cloud Functions - may, for a short period of time, create more instances than - the specified max instances limit. If your function cannot - tolerate this temporary behavior, you may want to factor in - a safety margin and set a lower max instances value than - your function can tolerate. - - See the `Max - Instances `__ - Guide for more details. - min_instances (int): - A lower bound for the number function - instances that may coexist at a given time. - vpc_connector (str): - The VPC Network Connector that this cloud function can - connect to. It can be either the fully-qualified URI, or the - short name of the network connector resource. The format of - this field is ``projects/*/locations/*/connectors/*`` - - This field is mutually exclusive with ``network`` field and - will eventually replace it. - - See `the VPC - documentation `__ - for more information on connecting Cloud projects. - vpc_connector_egress_settings (google.cloud.functions_v1.types.CloudFunction.VpcConnectorEgressSettings): - The egress settings for the connector, - controlling what traffic is diverted through it. - ingress_settings (google.cloud.functions_v1.types.CloudFunction.IngressSettings): - The ingress settings for the function, - controlling what traffic can reach it. - kms_key_name (str): - Resource name of a KMS crypto key (managed by the user) used - to encrypt/decrypt function resources. - - It must match the pattern - ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. - - If specified, you must also provide an artifact registry - repository using the ``docker_repository`` field that was - created with the same KMS crypto key. - - The following service accounts need to be granted the role - 'Cloud KMS CryptoKey Encrypter/Decrypter - (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the - Key/KeyRing/Project/Organization (least access preferred). - - 1. Google Cloud Functions service account - (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - - Required to protect the function's image. - 2. Google Storage service account - (service-{project_number}@gs-project-accounts.iam.gserviceaccount.com) - - Required to protect the function's source code. If this - service account does not exist, deploying a function - without a KMS key or retrieving the service agent name - provisions it. For more information, see - https://cloud.google.com/storage/docs/projects#service-agents - and - https://cloud.google.com/storage/docs/getting-service-agent#gsutil. - - Google Cloud Functions delegates access to service agents to - protect function resources in internal projects that are not - accessible by the end user. - build_worker_pool (str): - Name of the Cloud Build Custom Worker Pool that should be - used to build the function. The format of this field is - ``projects/{project}/locations/{region}/workerPools/{workerPool}`` - where ``{project}`` and ``{region}`` are the project id and - region respectively where the worker pool is defined and - ``{workerPool}`` is the short name of the worker pool. - - If the project id is not the same as the function, then the - Cloud Functions Service Agent - (``service-@gcf-admin-robot.iam.gserviceaccount.com``) - must be granted the role Cloud Build Custom Workers Builder - (``roles/cloudbuild.customworkers.builder``) in the project. - build_id (str): - Output only. The Cloud Build ID of the latest - successful deployment of the function. - build_name (str): - Output only. The Cloud Build Name of the function - deployment. - ``projects//locations//builds/``. - secret_environment_variables (Sequence[google.cloud.functions_v1.types.SecretEnvVar]): - Secret environment variables configuration. - secret_volumes (Sequence[google.cloud.functions_v1.types.SecretVolume]): - Secret volumes configuration. - source_token (str): - Input only. An identifier for Firebase - function sources. Disclaimer: This field is only - supported for Firebase function deployments. - docker_repository (str): - User managed repository created in Artifact Registry - optionally with a customer managed encryption key. If - specified, deployments will use Artifact Registry. If - unspecified and the deployment is eligible to use Artifact - Registry, GCF will create and use a repository named - 'gcf-artifacts' for every deployed region. This is the - repository to which the function docker image will be pushed - after it is built by Cloud Build. - - It must match the pattern - ``projects/{project}/locations/{location}/repositories/{repository}``. - - Cross-project repositories are not supported. Cross-location - repositories are not supported. Repository format must be - 'DOCKER'. - docker_registry (google.cloud.functions_v1.types.CloudFunction.DockerRegistry): - Docker Registry to use for this deployment. - - If ``docker_repository`` field is specified, this field will - be automatically set as ``ARTIFACT_REGISTRY``. If - unspecified, it currently defaults to - ``CONTAINER_REGISTRY``. This field may be overridden by the - backend for eligible deployments. - """ - class VpcConnectorEgressSettings(proto.Enum): - r"""Available egress settings. - - This controls what traffic is diverted through the VPC Access - Connector resource. By default PRIVATE_RANGES_ONLY will be used. - """ - VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED = 0 - PRIVATE_RANGES_ONLY = 1 - ALL_TRAFFIC = 2 - - class IngressSettings(proto.Enum): - r"""Available ingress settings. - - This controls what traffic can reach the function. - - If unspecified, ALLOW_ALL will be used. - """ - INGRESS_SETTINGS_UNSPECIFIED = 0 - ALLOW_ALL = 1 - ALLOW_INTERNAL_ONLY = 2 - ALLOW_INTERNAL_AND_GCLB = 3 - - class DockerRegistry(proto.Enum): - r"""Docker Registry to use for storing function Docker images.""" - DOCKER_REGISTRY_UNSPECIFIED = 0 - CONTAINER_REGISTRY = 1 - ARTIFACT_REGISTRY = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - source_archive_url = proto.Field( - proto.STRING, - number=3, - oneof='source_code', - ) - source_repository = proto.Field( - proto.MESSAGE, - number=4, - oneof='source_code', - message='SourceRepository', - ) - source_upload_url = proto.Field( - proto.STRING, - number=16, - oneof='source_code', - ) - https_trigger = proto.Field( - proto.MESSAGE, - number=5, - oneof='trigger', - message='HttpsTrigger', - ) - event_trigger = proto.Field( - proto.MESSAGE, - number=6, - oneof='trigger', - message='EventTrigger', - ) - status = proto.Field( - proto.ENUM, - number=7, - enum='CloudFunctionStatus', - ) - entry_point = proto.Field( - proto.STRING, - number=8, - ) - runtime = proto.Field( - proto.STRING, - number=19, - ) - timeout = proto.Field( - proto.MESSAGE, - number=9, - message=duration_pb2.Duration, - ) - available_memory_mb = proto.Field( - proto.INT32, - number=10, - ) - service_account_email = proto.Field( - proto.STRING, - number=11, - ) - update_time = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - version_id = proto.Field( - proto.INT64, - number=14, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=15, - ) - environment_variables = proto.MapField( - proto.STRING, - proto.STRING, - number=17, - ) - build_environment_variables = proto.MapField( - proto.STRING, - proto.STRING, - number=28, - ) - network = proto.Field( - proto.STRING, - number=18, - ) - max_instances = proto.Field( - proto.INT32, - number=20, - ) - min_instances = proto.Field( - proto.INT32, - number=32, - ) - vpc_connector = proto.Field( - proto.STRING, - number=22, - ) - vpc_connector_egress_settings = proto.Field( - proto.ENUM, - number=23, - enum=VpcConnectorEgressSettings, - ) - ingress_settings = proto.Field( - proto.ENUM, - number=24, - enum=IngressSettings, - ) - kms_key_name = proto.Field( - proto.STRING, - number=25, - ) - build_worker_pool = proto.Field( - proto.STRING, - number=26, - ) - build_id = proto.Field( - proto.STRING, - number=27, - ) - build_name = proto.Field( - proto.STRING, - number=33, - ) - secret_environment_variables = proto.RepeatedField( - proto.MESSAGE, - number=29, - message='SecretEnvVar', - ) - secret_volumes = proto.RepeatedField( - proto.MESSAGE, - number=30, - message='SecretVolume', - ) - source_token = proto.Field( - proto.STRING, - number=31, - ) - docker_repository = proto.Field( - proto.STRING, - number=34, - ) - docker_registry = proto.Field( - proto.ENUM, - number=35, - enum=DockerRegistry, - ) - - -class SourceRepository(proto.Message): - r"""Describes SourceRepository, used to represent parameters - related to source repository where a function is hosted. - - Attributes: - url (str): - The URL pointing to the hosted repository where the function - is defined. There are supported Cloud Source Repository URLs - in the following formats: - - To refer to a specific commit: - ``https://source.developers.google.com/projects/*/repos/*/revisions/*/paths/*`` - To refer to a moveable alias (branch): - ``https://source.developers.google.com/projects/*/repos/*/moveable-aliases/*/paths/*`` - In particular, to refer to HEAD use ``master`` moveable - alias. To refer to a specific fixed alias (tag): - ``https://source.developers.google.com/projects/*/repos/*/fixed-aliases/*/paths/*`` - - You may omit ``paths/*`` if you want to use the main - directory. - deployed_url (str): - Output only. The URL pointing to the hosted - repository where the function were defined at - the time of deployment. It always points to a - specific commit in the format described above. - """ - - url = proto.Field( - proto.STRING, - number=1, - ) - deployed_url = proto.Field( - proto.STRING, - number=2, - ) - - -class HttpsTrigger(proto.Message): - r"""Describes HttpsTrigger, could be used to connect web hooks to - function. - - Attributes: - url (str): - Output only. The deployed url for the - function. - security_level (google.cloud.functions_v1.types.HttpsTrigger.SecurityLevel): - The security level for the function. - """ - class SecurityLevel(proto.Enum): - r"""Available security level settings. - - This controls the methods to enforce security (HTTPS) on a URL. - - If unspecified, SECURE_OPTIONAL will be used. - """ - SECURITY_LEVEL_UNSPECIFIED = 0 - SECURE_ALWAYS = 1 - SECURE_OPTIONAL = 2 - - url = proto.Field( - proto.STRING, - number=1, - ) - security_level = proto.Field( - proto.ENUM, - number=2, - enum=SecurityLevel, - ) - - -class EventTrigger(proto.Message): - r"""Describes EventTrigger, used to request events be sent from - another service. - - Attributes: - event_type (str): - Required. The type of event to observe. For example: - ``providers/cloud.storage/eventTypes/object.change`` and - ``providers/cloud.pubsub/eventTypes/topic.publish``. - - Event types match pattern ``providers/*/eventTypes/*.*``. - The pattern contains: - - 1. namespace: For example, ``cloud.storage`` and - ``google.firebase.analytics``. - 2. resource type: The type of resource on which event - occurs. For example, the Google Cloud Storage API - includes the type ``object``. - 3. action: The action that generates the event. For example, - action for a Google Cloud Storage Object is 'change'. - These parts are lower case. - resource (str): - Required. The resource(s) from which to observe events, for - example, ``projects/_/buckets/myBucket``. - - Not all syntactically correct values are accepted by all - services. For example: - - 1. The authorization model must support it. Google Cloud - Functions only allows EventTriggers to be deployed that - observe resources in the same project as the - ``CloudFunction``. - 2. The resource type must match the pattern expected for an - ``event_type``. For example, an ``EventTrigger`` that has - an ``event_type`` of "google.pubsub.topic.publish" should - have a resource that matches Google Cloud Pub/Sub topics. - - Additionally, some services may support short names when - creating an ``EventTrigger``. These will always be returned - in the normalized "long" format. - - See each *service's* documentation for supported formats. - service (str): - The hostname of the service that should be observed. - - If no string is provided, the default service implementing - the API will be used. For example, - ``storage.googleapis.com`` is the default for all event - types in the ``google.storage`` namespace. - failure_policy (google.cloud.functions_v1.types.FailurePolicy): - Specifies policy for failed executions. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - resource = proto.Field( - proto.STRING, - number=2, - ) - service = proto.Field( - proto.STRING, - number=3, - ) - failure_policy = proto.Field( - proto.MESSAGE, - number=5, - message='FailurePolicy', - ) - - -class FailurePolicy(proto.Message): - r"""Describes the policy in case of function's execution failure. - If empty, then defaults to ignoring failures (i.e. not retrying - them). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - retry (google.cloud.functions_v1.types.FailurePolicy.Retry): - If specified, then the function will be - retried in case of a failure. - - This field is a member of `oneof`_ ``action``. - """ - - class Retry(proto.Message): - r"""Describes the retry policy in case of function's execution - failure. A function execution will be retried on any failure. A - failed execution will be retried up to 7 days with an - exponential backoff (capped at 10 seconds). - Retried execution is charged as any other execution. - - """ - - retry = proto.Field( - proto.MESSAGE, - number=1, - oneof='action', - message=Retry, - ) - - -class SecretEnvVar(proto.Message): - r"""Configuration for a secret environment variable. It has the - information necessary to fetch the secret value from secret - manager and expose it as an environment variable. - - Attributes: - key (str): - Name of the environment variable. - project_id (str): - Project identifier (preferrably project - number but can also be the project ID) of the - project that contains the secret. If not set, it - will be populated with the function's project - assuming that the secret exists in the same - project as of the function. - secret (str): - Name of the secret in secret manager (not the - full resource name). - version (str): - Version of the secret (version number or the - string 'latest'). It is recommended to use a - numeric version for secret environment variables - as any updates to the secret value is not - reflected until new instances start. - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - project_id = proto.Field( - proto.STRING, - number=2, - ) - secret = proto.Field( - proto.STRING, - number=3, - ) - version = proto.Field( - proto.STRING, - number=4, - ) - - -class SecretVolume(proto.Message): - r"""Configuration for a secret volume. It has the information - necessary to fetch the secret value from secret manager and make - it available as files mounted at the requested paths within the - application container. Secret value is not a part of the - configuration. Every filesystem read operation performs a lookup - in secret manager to retrieve the secret value. - - Attributes: - mount_path (str): - The path within the container to mount the secret volume. - For example, setting the mount_path as ``/etc/secrets`` - would mount the secret value files under the - ``/etc/secrets`` directory. This directory will also be - completely shadowed and unavailable to mount any other - secrets. - - Recommended mount paths: /etc/secrets Restricted mount - paths: /cloudsql, /dev/log, /pod, /proc, /var/log - project_id (str): - Project identifier (preferrably project - number but can also be the project ID) of the - project that contains the secret. If not set, it - will be populated with the function's project - assuming that the secret exists in the same - project as of the function. - secret (str): - Name of the secret in secret manager (not the - full resource name). - versions (Sequence[google.cloud.functions_v1.types.SecretVolume.SecretVersion]): - List of secret versions to mount for this secret. If empty, - the ``latest`` version of the secret will be made available - in a file named after the secret under the mount point. - """ - - class SecretVersion(proto.Message): - r"""Configuration for a single version. - - Attributes: - version (str): - Version of the secret (version number or the string - 'latest'). It is preferrable to use ``latest`` version with - secret volumes as secret value changes are reflected - immediately. - path (str): - Relative path of the file under the mount path where the - secret value for this version will be fetched and made - available. For example, setting the mount_path as - '/etc/secrets' and path as ``/secret_foo`` would mount the - secret value file at ``/etc/secrets/secret_foo``. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - path = proto.Field( - proto.STRING, - number=2, - ) - - mount_path = proto.Field( - proto.STRING, - number=1, - ) - project_id = proto.Field( - proto.STRING, - number=2, - ) - secret = proto.Field( - proto.STRING, - number=3, - ) - versions = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=SecretVersion, - ) - - -class CreateFunctionRequest(proto.Message): - r"""Request for the ``CreateFunction`` method. - - Attributes: - location (str): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - function (google.cloud.functions_v1.types.CloudFunction): - Required. Function to be created. - """ - - location = proto.Field( - proto.STRING, - number=1, - ) - function = proto.Field( - proto.MESSAGE, - number=2, - message='CloudFunction', - ) - - -class UpdateFunctionRequest(proto.Message): - r"""Request for the ``UpdateFunction`` method. - - Attributes: - function (google.cloud.functions_v1.types.CloudFunction): - Required. New version of the function. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields in ``CloudFunction`` that have - to be updated. - """ - - function = proto.Field( - proto.MESSAGE, - number=1, - message='CloudFunction', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetFunctionRequest(proto.Message): - r"""Request for the ``GetFunction`` method. - - Attributes: - name (str): - Required. The name of the function which - details should be obtained. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFunctionsRequest(proto.Message): - r"""Request for the ``ListFunctions`` method. - - Attributes: - parent (str): - The project and location from which the function should be - listed, specified in the format ``projects/*/locations/*`` - If you want to list functions in all locations, use "-" in - place of a location. When listing functions in all - locations, if one or more location(s) are unreachable, the - response will contain functions from all reachable locations - along with the names of any unreachable locations. - page_size (int): - Maximum number of functions to return per - call. - page_token (str): - The value returned by the last ``ListFunctionsResponse``; - indicates that this is a continuation of a prior - ``ListFunctions`` call, and that the system should return - the next page of data. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListFunctionsResponse(proto.Message): - r"""Response for the ``ListFunctions`` method. - - Attributes: - functions (Sequence[google.cloud.functions_v1.types.CloudFunction]): - The functions that match the request. - next_page_token (str): - If not empty, indicates that there may be more functions - that match the request; this value should be passed in a new - [google.cloud.functions.v1.ListFunctionsRequest][google.cloud.functions.v1.ListFunctionsRequest] - to get more functions. - unreachable (Sequence[str]): - Locations that could not be reached. The - response does not include any functions from - these locations. - """ - - @property - def raw_page(self): - return self - - functions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='CloudFunction', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - unreachable = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class DeleteFunctionRequest(proto.Message): - r"""Request for the ``DeleteFunction`` method. - - Attributes: - name (str): - Required. The name of the function which - should be deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CallFunctionRequest(proto.Message): - r"""Request for the ``CallFunction`` method. - - Attributes: - name (str): - Required. The name of the function to be - called. - data (str): - Required. Input to be passed to the function. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - data = proto.Field( - proto.STRING, - number=2, - ) - - -class CallFunctionResponse(proto.Message): - r"""Response of ``CallFunction`` method. - - Attributes: - execution_id (str): - Execution id of function invocation. - result (str): - Result populated for successful execution of - synchronous function. Will not be populated if - function does not return a result through - context. - error (str): - Either system or user-function generated - error. Set if execution was not successful. - """ - - execution_id = proto.Field( - proto.STRING, - number=1, - ) - result = proto.Field( - proto.STRING, - number=2, - ) - error = proto.Field( - proto.STRING, - number=3, - ) - - -class GenerateUploadUrlRequest(proto.Message): - r"""Request of ``GenerateSourceUploadUrl`` method. - - Attributes: - parent (str): - The project and location in which the Google Cloud Storage - signed URL should be generated, specified in the format - ``projects/*/locations/*``. - kms_key_name (str): - Resource name of a KMS crypto key (managed by the user) used - to encrypt/decrypt function source code objects in staging - Cloud Storage buckets. When you generate an upload url and - upload your source code, it gets copied to a staging Cloud - Storage bucket in an internal regional project. The source - code is then copied to a versioned directory in the sources - bucket in the consumer project during the function - deployment. - - It must match the pattern - ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. - - The Google Cloud Functions service account - (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - must be granted the role 'Cloud KMS CryptoKey - Encrypter/Decrypter - (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the - Key/KeyRing/Project/Organization (least access preferred). - GCF will delegate access to the Google Storage service - account in the internal project. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - kms_key_name = proto.Field( - proto.STRING, - number=2, - ) - - -class GenerateUploadUrlResponse(proto.Message): - r"""Response of ``GenerateSourceUploadUrl`` method. - - Attributes: - upload_url (str): - The generated Google Cloud Storage signed URL - that should be used for a function source code - upload. The uploaded file should be a zip - archive which contains a function. - """ - - upload_url = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateDownloadUrlRequest(proto.Message): - r"""Request of ``GenerateDownloadUrl`` method. - - Attributes: - name (str): - The name of function for which source code - Google Cloud Storage signed URL should be - generated. - version_id (int): - The optional version of function. If not set, - default, current version is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - version_id = proto.Field( - proto.UINT64, - number=2, - ) - - -class GenerateDownloadUrlResponse(proto.Message): - r"""Response of ``GenerateDownloadUrl`` method. - - Attributes: - download_url (str): - The generated Google Cloud Storage signed URL - that should be used for function source code - download. - """ - - download_url = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py deleted file mode 100644 index ab59796..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py +++ /dev/null @@ -1,108 +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 any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.functions.v1', - manifest={ - 'OperationType', - 'OperationMetadataV1', - }, -) - - -class OperationType(proto.Enum): - r"""A type of an operation.""" - OPERATION_UNSPECIFIED = 0 - CREATE_FUNCTION = 1 - UPDATE_FUNCTION = 2 - DELETE_FUNCTION = 3 - - -class OperationMetadataV1(proto.Message): - r"""Metadata describing an [Operation][google.longrunning.Operation] - - Attributes: - target (str): - Target of the operation - for example - ``projects/project-1/locations/region-1/functions/function-1`` - type_ (google.cloud.functions_v1.types.OperationType): - Type of operation. - request (google.protobuf.any_pb2.Any): - The original request that started the - operation. - version_id (int): - Version id of the function created or updated - by an API call. This field is only populated for - Create and Update operations. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update timestamp of the operation. - build_id (str): - The Cloud Build ID of the function created or - updated by an API call. This field is only - populated for Create and Update operations. - source_token (str): - An identifier for Firebase function sources. - Disclaimer: This field is only supported for - Firebase function deployments. - build_name (str): - The Cloud Build Name of the function deployment. This field - is only populated for Create and Update operations. - ``projects//locations//builds/``. - """ - - target = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - enum='OperationType', - ) - request = proto.Field( - proto.MESSAGE, - number=3, - message=any_pb2.Any, - ) - version_id = proto.Field( - proto.INT64, - number=4, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - build_id = proto.Field( - proto.STRING, - number=6, - ) - source_token = proto.Field( - proto.STRING, - number=7, - ) - build_name = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 38940e8..0000000 --- a/owl-bot-staging/v1/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', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/functions_v1/', - '--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/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py deleted file mode 100644 index f6b67dc..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] -from google.cloud import functions_v1 - - -async def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = await client.call_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py deleted file mode 100644 index 7cddbe7..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] -from google.cloud import functions_v1 - - -def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = client.call_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py deleted file mode 100644 index dd6b621..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py +++ /dev/null @@ -1,53 +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 CreateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] -from google.cloud import functions_v1 - - -async def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py deleted file mode 100644 index 117d443..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py +++ /dev/null @@ -1,53 +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 CreateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] -from google.cloud import functions_v1 - - -def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py deleted file mode 100644 index 3051534..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] -from google.cloud import functions_v1 - - -async def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py deleted file mode 100644 index 2262e7b..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] -from google.cloud import functions_v1 - - -def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py deleted file mode 100644 index 30f6889..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py +++ /dev/null @@ -1,44 +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 GenerateDownloadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] -from google.cloud import functions_v1 - - -async def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = await client.generate_download_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py deleted file mode 100644 index fbc886f..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py +++ /dev/null @@ -1,44 +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 GenerateDownloadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] -from google.cloud import functions_v1 - - -def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = client.generate_download_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py deleted file mode 100644 index 6b19431..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py +++ /dev/null @@ -1,44 +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 GenerateUploadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] -from google.cloud import functions_v1 - - -async def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = await client.generate_upload_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py deleted file mode 100644 index 6e9590a..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py +++ /dev/null @@ -1,44 +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 GenerateUploadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] -from google.cloud import functions_v1 - - -def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = client.generate_upload_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py deleted file mode 100644 index f89b7da..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] -from google.cloud import functions_v1 - - -async def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py deleted file mode 100644 index 761c41d..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] -from google.cloud import functions_v1 - - -def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = client.get_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py deleted file mode 100644 index 09d1b8a..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py deleted file mode 100644 index eafe7b7..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py deleted file mode 100644 index 9a3cd36..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] -from google.cloud import functions_v1 - - -async def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py deleted file mode 100644 index 98b3760..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] -from google.cloud import functions_v1 - - -def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py deleted file mode 100644 index 2d1128e..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py deleted file mode 100644 index b8b14ab..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py deleted file mode 100644 index 936744f..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py +++ /dev/null @@ -1,47 +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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py deleted file mode 100644 index c5766f3..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py +++ /dev/null @@ -1,47 +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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py deleted file mode 100644 index 4863198..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py +++ /dev/null @@ -1,52 +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 UpdateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] -from google.cloud import functions_v1 - - -async def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py deleted file mode 100644 index 11809c3..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py +++ /dev/null @@ -1,52 +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 UpdateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] -from google.cloud import functions_v1 - - -def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json deleted file mode 100644 index 9c991cf..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json +++ /dev/null @@ -1,1753 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.functions.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-functions" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.call_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CallFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CallFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", - "shortName": "call_function" - }, - "description": "Sample for CallFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.call_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CallFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CallFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", - "shortName": "call_function" - }, - "description": "Sample for CallFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.create_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CreateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CreateFunctionRequest" - }, - { - "name": "location", - "type": "str" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_function" - }, - "description": "Sample for CreateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.create_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CreateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CreateFunctionRequest" - }, - { - "name": "location", - "type": "str" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_function" - }, - "description": "Sample for CreateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.delete_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "DeleteFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_function" - }, - "description": "Sample for DeleteFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.delete_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "DeleteFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_function" - }, - "description": "Sample for DeleteFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_download_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateDownloadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", - "shortName": "generate_download_url" - }, - "description": "Sample for GenerateDownloadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_download_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateDownloadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", - "shortName": "generate_download_url" - }, - "description": "Sample for GenerateDownloadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_upload_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateUploadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", - "shortName": "generate_upload_url" - }, - "description": "Sample for GenerateUploadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_upload_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateUploadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", - "shortName": "generate_upload_url" - }, - "description": "Sample for GenerateUploadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GetFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CloudFunction", - "shortName": "get_function" - }, - "description": "Sample for GetFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GetFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CloudFunction", - "shortName": "get_function" - }, - "description": "Sample for GetFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.list_functions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "ListFunctions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.ListFunctionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager", - "shortName": "list_functions" - }, - "description": "Sample for ListFunctions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.list_functions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "ListFunctions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.ListFunctionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager", - "shortName": "list_functions" - }, - "description": "Sample for ListFunctions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.set_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 43, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 44, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 43, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 44, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.update_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "UpdateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_function" - }, - "description": "Sample for UpdateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.update_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "UpdateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_function" - }, - "description": "Sample for UpdateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py deleted file mode 100644 index 6dc057c..0000000 --- a/owl-bot-staging/v1/scripts/fixup_functions_v1_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 functionsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'call_function': ('name', 'data', ), - 'create_function': ('location', 'function', ), - 'delete_function': ('name', ), - 'generate_download_url': ('name', 'version_id', ), - 'generate_upload_url': ('parent', 'kms_key_name', ), - 'get_function': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'list_functions': ('parent', 'page_size', 'page_token', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_function': ('function', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=functionsCallTransformer(), -): - """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 functions client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index 820b19a..0000000 --- a/owl-bot-staging/v1/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-functions', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-functions", - 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] >= 2.8.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.4, < 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/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/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/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/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/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/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/v1/tests/unit/gapic/functions_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__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/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py deleted file mode 100644 index b5d30d9..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py +++ /dev/null @@ -1,3682 +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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import 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.functions_v1.services.cloud_functions_service import CloudFunctionsServiceAsyncClient -from google.cloud.functions_v1.services.cloud_functions_service import CloudFunctionsServiceClient -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.services.cloud_functions_service import transports -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -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 CloudFunctionsServiceClient._get_default_mtls_endpoint(None) is None - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CloudFunctionsServiceClient, "grpc"), - (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CloudFunctionsServiceClient, "grpc"), - (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:443' - ) - - -def test_cloud_functions_service_client_get_transport_class(): - transport = CloudFunctionsServiceClient.get_transport_class() - available_transports = [ - transports.CloudFunctionsServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CloudFunctionsServiceClient.get_transport_class("grpc") - assert transport == transports.CloudFunctionsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) -def test_cloud_functions_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CloudFunctionsServiceClient, '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(CloudFunctionsServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - 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, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "true"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "false"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_cloud_functions_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CloudFunctionsServiceClient, CloudFunctionsServiceAsyncClient -]) -@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) -def test_cloud_functions_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_cloud_functions_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_cloud_functions_service_client_client_options_from_dict(): - with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CloudFunctionsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_cloud_functions_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudfunctions.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="cloudfunctions.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - functions.ListFunctionsRequest, - dict, -]) -def test_list_functions(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_functions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.ListFunctionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFunctionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_functions_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 = CloudFunctionsServiceClient( - 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_functions), - '__call__') as call: - client.list_functions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - -@pytest.mark.asyncio -async def test_list_functions_async(transport: str = 'grpc_asyncio', request_type=functions.ListFunctionsRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_functions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFunctionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_functions_async_from_dict(): - await test_list_functions_async(request_type=dict) - - -def test_list_functions_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.ListFunctionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: - call.return_value = functions.ListFunctionsResponse() - client.list_functions(request) - - # Establish that the 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_functions_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.ListFunctionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse()) - await client.list_functions(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_functions_pager(transport_name: str = "grpc"): - client = CloudFunctionsServiceClient( - 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_functions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_functions(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, functions.CloudFunction) - for i in results) -def test_list_functions_pages(transport_name: str = "grpc"): - client = CloudFunctionsServiceClient( - 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_functions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - pages = list(client.list_functions(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_functions_async_pager(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_functions(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, functions.CloudFunction) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_functions_async_pages(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_functions(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", [ - functions.GetFunctionRequest, - dict, -]) -def test_get_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CloudFunction( - name='name_value', - description='description_value', - status=functions.CloudFunctionStatus.ACTIVE, - entry_point='entry_point_value', - runtime='runtime_value', - available_memory_mb=1991, - service_account_email='service_account_email_value', - version_id=1074, - network='network_value', - max_instances=1389, - min_instances=1387, - vpc_connector='vpc_connector_value', - vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, - ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, - kms_key_name='kms_key_name_value', - build_worker_pool='build_worker_pool_value', - build_id='build_id_value', - build_name='build_name_value', - source_token='source_token_value', - docker_repository='docker_repository_value', - docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, - source_archive_url='source_archive_url_value', - https_trigger=functions.HttpsTrigger(url='url_value'), - ) - response = client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CloudFunction) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.status == functions.CloudFunctionStatus.ACTIVE - assert response.entry_point == 'entry_point_value' - assert response.runtime == 'runtime_value' - assert response.available_memory_mb == 1991 - assert response.service_account_email == 'service_account_email_value' - assert response.version_id == 1074 - assert response.network == 'network_value' - assert response.max_instances == 1389 - assert response.min_instances == 1387 - assert response.vpc_connector == 'vpc_connector_value' - assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY - assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL - assert response.kms_key_name == 'kms_key_name_value' - assert response.build_worker_pool == 'build_worker_pool_value' - assert response.build_id == 'build_id_value' - assert response.build_name == 'build_name_value' - assert response.source_token == 'source_token_value' - assert response.docker_repository == 'docker_repository_value' - assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY - - -def test_get_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.get_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - -@pytest.mark.asyncio -async def test_get_function_async(transport: str = 'grpc_asyncio', request_type=functions.GetFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction( - name='name_value', - description='description_value', - status=functions.CloudFunctionStatus.ACTIVE, - entry_point='entry_point_value', - runtime='runtime_value', - available_memory_mb=1991, - service_account_email='service_account_email_value', - version_id=1074, - network='network_value', - max_instances=1389, - min_instances=1387, - vpc_connector='vpc_connector_value', - vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, - ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, - kms_key_name='kms_key_name_value', - build_worker_pool='build_worker_pool_value', - build_id='build_id_value', - build_name='build_name_value', - source_token='source_token_value', - docker_repository='docker_repository_value', - docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, - )) - response = await client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CloudFunction) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.status == functions.CloudFunctionStatus.ACTIVE - assert response.entry_point == 'entry_point_value' - assert response.runtime == 'runtime_value' - assert response.available_memory_mb == 1991 - assert response.service_account_email == 'service_account_email_value' - assert response.version_id == 1074 - assert response.network == 'network_value' - assert response.max_instances == 1389 - assert response.min_instances == 1387 - assert response.vpc_connector == 'vpc_connector_value' - assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY - assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL - assert response.kms_key_name == 'kms_key_name_value' - assert response.build_worker_pool == 'build_worker_pool_value' - assert response.build_id == 'build_id_value' - assert response.build_name == 'build_name_value' - assert response.source_token == 'source_token_value' - assert response.docker_repository == 'docker_repository_value' - assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY - - -@pytest.mark.asyncio -async def test_get_function_async_from_dict(): - await test_get_function_async(request_type=dict) - - -def test_get_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GetFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - call.return_value = functions.CloudFunction() - client.get_function(request) - - # Establish that the 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_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GetFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) - await client.get_function(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_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CloudFunction() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_function( - 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_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.GetFunctionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CloudFunction() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_function( - 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_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.GetFunctionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.CreateFunctionRequest, - dict, -]) -def test_create_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.create_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - -@pytest.mark.asyncio -async def test_create_function_async(transport: str = 'grpc_asyncio', request_type=functions.CreateFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__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_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_function_async_from_dict(): - await test_create_function_async(request_type=dict) - - -def test_create_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CreateFunctionRequest() - - request.location = 'location_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_function(request) - - # Establish that the 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', - 'location=location_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CreateFunctionRequest() - - request.location = 'location_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_function(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', - 'location=location_value', - ) in kw['metadata'] - - -def test_create_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__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_function( - location='location_value', - function=functions.CloudFunction(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].location - mock_val = 'location_value' - assert arg == mock_val - arg = args[0].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - - -def test_create_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.CreateFunctionRequest(), - location='location_value', - function=functions.CloudFunction(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__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_function( - location='location_value', - function=functions.CloudFunction(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].location - mock_val = 'location_value' - assert arg == mock_val - arg = args[0].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.CreateFunctionRequest(), - location='location_value', - function=functions.CloudFunction(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - functions.UpdateFunctionRequest, - dict, -]) -def test_update_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.update_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - -@pytest.mark.asyncio -async def test_update_function_async(transport: str = 'grpc_asyncio', request_type=functions.UpdateFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__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_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_function_async_from_dict(): - await test_update_function_async(request_type=dict) - - -def test_update_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.UpdateFunctionRequest() - - request.function.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_function(request) - - # Establish that the 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', - 'function.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.UpdateFunctionRequest() - - request.function.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_function(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', - 'function.name=name_value', - ) in kw['metadata'] - - -def test_update_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__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_function( - function=functions.CloudFunction(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].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - - -def test_update_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.UpdateFunctionRequest(), - function=functions.CloudFunction(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__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_function( - function=functions.CloudFunction(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].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.UpdateFunctionRequest(), - function=functions.CloudFunction(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - functions.DeleteFunctionRequest, - dict, -]) -def test_delete_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.delete_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - -@pytest.mark.asyncio -async def test_delete_function_async(transport: str = 'grpc_asyncio', request_type=functions.DeleteFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__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_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_function_async_from_dict(): - await test_delete_function_async(request_type=dict) - - -def test_delete_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.DeleteFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_function(request) - - # Establish that the 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_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.DeleteFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_function(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_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__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_function( - 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_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.DeleteFunctionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__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_function( - 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_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.DeleteFunctionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.CallFunctionRequest, - dict, -]) -def test_call_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse( - execution_id='execution_id_value', - result='result_value', - error='error_value', - ) - response = client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CallFunctionResponse) - assert response.execution_id == 'execution_id_value' - assert response.result == 'result_value' - assert response.error == 'error_value' - - -def test_call_function_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 = CloudFunctionsServiceClient( - 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.call_function), - '__call__') as call: - client.call_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - -@pytest.mark.asyncio -async def test_call_function_async(transport: str = 'grpc_asyncio', request_type=functions.CallFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse( - execution_id='execution_id_value', - result='result_value', - error='error_value', - )) - response = await client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CallFunctionResponse) - assert response.execution_id == 'execution_id_value' - assert response.result == 'result_value' - assert response.error == 'error_value' - - -@pytest.mark.asyncio -async def test_call_function_async_from_dict(): - await test_call_function_async(request_type=dict) - - -def test_call_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CallFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - call.return_value = functions.CallFunctionResponse() - client.call_function(request) - - # Establish that the 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_call_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CallFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) - await client.call_function(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_call_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.call_function( - name='name_value', - data='data_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 - arg = args[0].data - mock_val = 'data_value' - assert arg == mock_val - - -def test_call_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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.call_function( - functions.CallFunctionRequest(), - name='name_value', - data='data_value', - ) - -@pytest.mark.asyncio -async def test_call_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.call_function( - name='name_value', - data='data_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 - arg = args[0].data - mock_val = 'data_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_call_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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.call_function( - functions.CallFunctionRequest(), - name='name_value', - data='data_value', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateUploadUrlRequest, - dict, -]) -def test_generate_upload_url(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.GenerateUploadUrlResponse( - upload_url='upload_url_value', - ) - response = client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateUploadUrlResponse) - assert response.upload_url == 'upload_url_value' - - -def test_generate_upload_url_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 = CloudFunctionsServiceClient( - 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.generate_upload_url), - '__call__') as call: - client.generate_upload_url() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - -@pytest.mark.asyncio -async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateUploadUrlRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse( - upload_url='upload_url_value', - )) - response = await client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateUploadUrlResponse) - assert response.upload_url == 'upload_url_value' - - -@pytest.mark.asyncio -async def test_generate_upload_url_async_from_dict(): - await test_generate_upload_url_async(request_type=dict) - - -def test_generate_upload_url_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateUploadUrlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - call.return_value = functions.GenerateUploadUrlResponse() - client.generate_upload_url(request) - - # Establish that the 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_generate_upload_url_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateUploadUrlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse()) - await client.generate_upload_url(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'] - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateDownloadUrlRequest, - dict, -]) -def test_generate_download_url(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.GenerateDownloadUrlResponse( - download_url='download_url_value', - ) - response = client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateDownloadUrlResponse) - assert response.download_url == 'download_url_value' - - -def test_generate_download_url_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 = CloudFunctionsServiceClient( - 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.generate_download_url), - '__call__') as call: - client.generate_download_url() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - -@pytest.mark.asyncio -async def test_generate_download_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateDownloadUrlRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse( - download_url='download_url_value', - )) - response = await client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateDownloadUrlResponse) - assert response.download_url == 'download_url_value' - - -@pytest.mark.asyncio -async def test_generate_download_url_async_from_dict(): - await test_generate_download_url_async(request_type=dict) - - -def test_generate_download_url_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateDownloadUrlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - call.return_value = functions.GenerateDownloadUrlResponse() - client.generate_download_url(request) - - # Establish that the 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_generate_download_url_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateDownloadUrlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse()) - await client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceClient( - 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.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceClient( - 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.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceClient( - 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.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CloudFunctionsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, -]) -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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CloudFunctionsServiceGrpcTransport, - ) - -def test_cloud_functions_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CloudFunctionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_cloud_functions_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CloudFunctionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_functions', - 'get_function', - 'create_function', - 'update_function', - 'delete_function', - 'call_function', - 'generate_upload_url', - 'generate_download_url', - 'set_iam_policy', - 'get_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_cloud_functions_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudFunctionsServiceTransport( - 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_cloud_functions_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudFunctionsServiceTransport() - adc.assert_called_once() - - -def test_cloud_functions_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CloudFunctionsServiceClient() - 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.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, - ], -) -def test_cloud_functions_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, - transports.CloudFunctionsServiceRestTransport, - ], -) -def test_cloud_functions_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CloudFunctionsServiceGrpcTransport, grpc_helpers), - (transports.CloudFunctionsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_cloud_functions_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "cloudfunctions.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="cloudfunctions.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_cloud_functions_service_host_no_port(transport_name): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_cloud_functions_service_host_with_port(transport_name): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:8000' - ) - -def test_cloud_functions_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CloudFunctionsServiceGrpcTransport( - 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_cloud_functions_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( - 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.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_cloud_functions_service_grpc_lro_client(): - client = CloudFunctionsServiceClient( - 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_cloud_functions_service_grpc_lro_async_client(): - client = CloudFunctionsServiceAsyncClient( - 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_cloud_function_path(): - project = "squid" - location = "clam" - function = "whelk" - expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) - actual = CloudFunctionsServiceClient.cloud_function_path(project, location, function) - assert expected == actual - - -def test_parse_cloud_function_path(): - expected = { - "project": "octopus", - "location": "oyster", - "function": "nudibranch", - } - path = CloudFunctionsServiceClient.cloud_function_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_cloud_function_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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_crypto_key_path(path) - assert expected == actual - -def test_repository_path(): - project = "whelk" - location = "octopus" - repository = "oyster" - expected = "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) - actual = CloudFunctionsServiceClient.repository_path(project, location, repository) - assert expected == actual - - -def test_parse_repository_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "repository": "mussel", - } - path = CloudFunctionsServiceClient.repository_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_repository_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CloudFunctionsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = CloudFunctionsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = CloudFunctionsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = CloudFunctionsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CloudFunctionsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = CloudFunctionsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = CloudFunctionsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = CloudFunctionsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CloudFunctionsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = CloudFunctionsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.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.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CloudFunctionsServiceClient.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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceClient( - 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", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport), -]) -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, - api_audience=None, - ) diff --git a/tests/unit/gapic/functions_v1/test_cloud_functions_service.py b/tests/unit/gapic/functions_v1/test_cloud_functions_service.py index 7db328f..754e700 100644 --- a/tests/unit/gapic/functions_v1/test_cloud_functions_service.py +++ b/tests/unit/gapic/functions_v1/test_cloud_functions_service.py @@ -249,6 +249,7 @@ def test_cloud_functions_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -266,6 +267,7 @@ def test_cloud_functions_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -283,6 +285,7 @@ def test_cloud_functions_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -312,6 +315,25 @@ def test_cloud_functions_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -389,6 +411,7 @@ def test_cloud_functions_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -423,6 +446,7 @@ def test_cloud_functions_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -445,6 +469,7 @@ def test_cloud_functions_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -563,6 +588,7 @@ def test_cloud_functions_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -601,6 +627,7 @@ def test_cloud_functions_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -621,6 +648,7 @@ def test_cloud_functions_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -659,6 +687,7 @@ def test_cloud_functions_service_client_create_channel_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # test that the credentials from file are saved and used as the credentials. @@ -3373,6 +3402,29 @@ def test_cloud_functions_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, + transports.CloudFunctionsServiceRestTransport, + ], +) +def test_cloud_functions_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -3943,4 +3995,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) From 1af216bef372fab8036b48e426c272a1f7cbd233 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 5 Jul 2022 23:38:24 +0000 Subject: [PATCH 03/16] chore: use gapic-generator-python 1.1.1 PiperOrigin-RevId: 459095142 Source-Link: https://github.com/googleapis/googleapis/commit/4f1be992601ed740a581a32cedc4e7b6c6a27793 Source-Link: https://github.com/googleapis/googleapis-gen/commit/ae686d9cde4fc3e36d0ac02efb8643b15890c1ed Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYWU2ODZkOWNkZTRmYzNlMzZkMGFjMDJlZmI4NjQzYjE1ODkwYzFlZCJ9 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/.flake8 | 33 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 ++ .../functions_v1/cloud_functions_service.rst | 10 + .../v1/docs/functions_v1/services.rst | 6 + .../v1/docs/functions_v1/types.rst | 7 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/google/cloud/functions/__init__.py | 67 + .../v1/google/cloud/functions/py.typed | 2 + .../v1/google/cloud/functions_v1/__init__.py | 68 + .../cloud/functions_v1/gapic_metadata.json | 133 + .../v1/google/cloud/functions_v1/py.typed | 2 + .../cloud/functions_v1/services/__init__.py | 15 + .../cloud_functions_service/__init__.py | 22 + .../cloud_functions_service/async_client.py | 1423 +++++++ .../cloud_functions_service/client.py | 1613 ++++++++ .../cloud_functions_service/pagers.py | 139 + .../transports/__init__.py | 33 + .../transports/base.py | 331 ++ .../transports/grpc.py | 593 +++ .../transports/grpc_asyncio.py | 592 +++ .../cloud/functions_v1/types/__init__.py | 66 + .../cloud/functions_v1/types/functions.py | 1067 +++++ .../cloud/functions_v1/types/operations.py | 108 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 180 + ...d_functions_service_call_function_async.py | 46 + ...ud_functions_service_call_function_sync.py | 46 + ...functions_service_create_function_async.py | 53 + ..._functions_service_create_function_sync.py | 53 + ...functions_service_delete_function_async.py | 49 + ..._functions_service_delete_function_sync.py | 49 + ...ons_service_generate_download_url_async.py | 44 + ...ions_service_generate_download_url_sync.py | 44 + ...tions_service_generate_upload_url_async.py | 44 + ...ctions_service_generate_upload_url_sync.py | 44 + ...ud_functions_service_get_function_async.py | 45 + ...oud_functions_service_get_function_sync.py | 45 + ..._functions_service_get_iam_policy_async.py | 46 + ...d_functions_service_get_iam_policy_sync.py | 46 + ..._functions_service_list_functions_async.py | 45 + ...d_functions_service_list_functions_sync.py | 45 + ..._functions_service_set_iam_policy_async.py | 46 + ...d_functions_service_set_iam_policy_sync.py | 46 + ...ions_service_test_iam_permissions_async.py | 47 + ...tions_service_test_iam_permissions_sync.py | 47 + ...functions_service_update_function_async.py | 52 + ..._functions_service_update_function_sync.py | 52 + .../snippet_metadata_functions_v1.json | 1753 ++++++++ .../v1/scripts/fixup_functions_v1_keywords.py | 186 + owl-bot-staging/v1/setup.py | 60 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/functions_v1/__init__.py | 16 + .../test_cloud_functions_service.py | 3681 +++++++++++++++++ 58 files changed, 13742 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/.flake8 create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst create mode 100644 owl-bot-staging/v1/docs/functions_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/functions_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/cloud/functions/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json create mode 100644 owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..ca93bdf --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/functions/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 0000000..9e8399a --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/functions *.py +recursive-include google/cloud/functions_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..533650a --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Functions 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 Functions API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..3464a12 --- /dev/null +++ b/owl-bot-staging/v1/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-functions 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-functions" +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-functions-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-functions.tex", + u"google-cloud-functions 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-functions", + u"Google Cloud Functions 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-functions", + u"google-cloud-functions Documentation", + author, + "google-cloud-functions", + "GAPIC library for Google Cloud Functions API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst b/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst new file mode 100644 index 0000000..36d0114 --- /dev/null +++ b/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst @@ -0,0 +1,10 @@ +CloudFunctionsService +--------------------------------------- + +.. automodule:: google.cloud.functions_v1.services.cloud_functions_service + :members: + :inherited-members: + +.. automodule:: google.cloud.functions_v1.services.cloud_functions_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/functions_v1/services.rst b/owl-bot-staging/v1/docs/functions_v1/services.rst new file mode 100644 index 0000000..89ae970 --- /dev/null +++ b/owl-bot-staging/v1/docs/functions_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Functions v1 API +========================================== +.. toctree:: + :maxdepth: 2 + + cloud_functions_service diff --git a/owl-bot-staging/v1/docs/functions_v1/types.rst b/owl-bot-staging/v1/docs/functions_v1/types.rst new file mode 100644 index 0000000..bebdfe9 --- /dev/null +++ b/owl-bot-staging/v1/docs/functions_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Functions v1 API +======================================= + +.. automodule:: google.cloud.functions_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..dc30f6d --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + functions_v1/services + functions_v1/types diff --git a/owl-bot-staging/v1/google/cloud/functions/__init__.py b/owl-bot-staging/v1/google/cloud/functions/__init__.py new file mode 100644 index 0000000..c34f3b0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions/__init__.py @@ -0,0 +1,67 @@ +# -*- 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.functions_v1.services.cloud_functions_service.client import CloudFunctionsServiceClient +from google.cloud.functions_v1.services.cloud_functions_service.async_client import CloudFunctionsServiceAsyncClient + +from google.cloud.functions_v1.types.functions import CallFunctionRequest +from google.cloud.functions_v1.types.functions import CallFunctionResponse +from google.cloud.functions_v1.types.functions import CloudFunction +from google.cloud.functions_v1.types.functions import CreateFunctionRequest +from google.cloud.functions_v1.types.functions import DeleteFunctionRequest +from google.cloud.functions_v1.types.functions import EventTrigger +from google.cloud.functions_v1.types.functions import FailurePolicy +from google.cloud.functions_v1.types.functions import GenerateDownloadUrlRequest +from google.cloud.functions_v1.types.functions import GenerateDownloadUrlResponse +from google.cloud.functions_v1.types.functions import GenerateUploadUrlRequest +from google.cloud.functions_v1.types.functions import GenerateUploadUrlResponse +from google.cloud.functions_v1.types.functions import GetFunctionRequest +from google.cloud.functions_v1.types.functions import HttpsTrigger +from google.cloud.functions_v1.types.functions import ListFunctionsRequest +from google.cloud.functions_v1.types.functions import ListFunctionsResponse +from google.cloud.functions_v1.types.functions import SecretEnvVar +from google.cloud.functions_v1.types.functions import SecretVolume +from google.cloud.functions_v1.types.functions import SourceRepository +from google.cloud.functions_v1.types.functions import UpdateFunctionRequest +from google.cloud.functions_v1.types.functions import CloudFunctionStatus +from google.cloud.functions_v1.types.operations import OperationMetadataV1 +from google.cloud.functions_v1.types.operations import OperationType + +__all__ = ('CloudFunctionsServiceClient', + 'CloudFunctionsServiceAsyncClient', + 'CallFunctionRequest', + 'CallFunctionResponse', + 'CloudFunction', + 'CreateFunctionRequest', + 'DeleteFunctionRequest', + 'EventTrigger', + 'FailurePolicy', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GetFunctionRequest', + 'HttpsTrigger', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'SecretEnvVar', + 'SecretVolume', + 'SourceRepository', + 'UpdateFunctionRequest', + 'CloudFunctionStatus', + 'OperationMetadataV1', + 'OperationType', +) diff --git a/owl-bot-staging/v1/google/cloud/functions/py.typed b/owl-bot-staging/v1/google/cloud/functions/py.typed new file mode 100644 index 0000000..982ebb1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py new file mode 100644 index 0000000..87351c6 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py @@ -0,0 +1,68 @@ +# -*- 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.cloud_functions_service import CloudFunctionsServiceClient +from .services.cloud_functions_service import CloudFunctionsServiceAsyncClient + +from .types.functions import CallFunctionRequest +from .types.functions import CallFunctionResponse +from .types.functions import CloudFunction +from .types.functions import CreateFunctionRequest +from .types.functions import DeleteFunctionRequest +from .types.functions import EventTrigger +from .types.functions import FailurePolicy +from .types.functions import GenerateDownloadUrlRequest +from .types.functions import GenerateDownloadUrlResponse +from .types.functions import GenerateUploadUrlRequest +from .types.functions import GenerateUploadUrlResponse +from .types.functions import GetFunctionRequest +from .types.functions import HttpsTrigger +from .types.functions import ListFunctionsRequest +from .types.functions import ListFunctionsResponse +from .types.functions import SecretEnvVar +from .types.functions import SecretVolume +from .types.functions import SourceRepository +from .types.functions import UpdateFunctionRequest +from .types.functions import CloudFunctionStatus +from .types.operations import OperationMetadataV1 +from .types.operations import OperationType + +__all__ = ( + 'CloudFunctionsServiceAsyncClient', +'CallFunctionRequest', +'CallFunctionResponse', +'CloudFunction', +'CloudFunctionStatus', +'CloudFunctionsServiceClient', +'CreateFunctionRequest', +'DeleteFunctionRequest', +'EventTrigger', +'FailurePolicy', +'GenerateDownloadUrlRequest', +'GenerateDownloadUrlResponse', +'GenerateUploadUrlRequest', +'GenerateUploadUrlResponse', +'GetFunctionRequest', +'HttpsTrigger', +'ListFunctionsRequest', +'ListFunctionsResponse', +'OperationMetadataV1', +'OperationType', +'SecretEnvVar', +'SecretVolume', +'SourceRepository', +'UpdateFunctionRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json new file mode 100644 index 0000000..5745d05 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json @@ -0,0 +1,133 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.functions_v1", + "protoPackage": "google.cloud.functions.v1", + "schema": "1.0", + "services": { + "CloudFunctionsService": { + "clients": { + "grpc": { + "libraryClient": "CloudFunctionsServiceClient", + "rpcs": { + "CallFunction": { + "methods": [ + "call_function" + ] + }, + "CreateFunction": { + "methods": [ + "create_function" + ] + }, + "DeleteFunction": { + "methods": [ + "delete_function" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "generate_download_url" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "generate_upload_url" + ] + }, + "GetFunction": { + "methods": [ + "get_function" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListFunctions": { + "methods": [ + "list_functions" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFunction": { + "methods": [ + "update_function" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudFunctionsServiceAsyncClient", + "rpcs": { + "CallFunction": { + "methods": [ + "call_function" + ] + }, + "CreateFunction": { + "methods": [ + "create_function" + ] + }, + "DeleteFunction": { + "methods": [ + "delete_function" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "generate_download_url" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "generate_upload_url" + ] + }, + "GetFunction": { + "methods": [ + "get_function" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListFunctions": { + "methods": [ + "list_functions" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFunction": { + "methods": [ + "update_function" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/py.typed b/owl-bot-staging/v1/google/cloud/functions_v1/py.typed new file mode 100644 index 0000000..982ebb1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/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/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py new file mode 100644 index 0000000..d784dc7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__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 CloudFunctionsServiceClient +from .async_client import CloudFunctionsServiceAsyncClient + +__all__ = ( + 'CloudFunctionsServiceClient', + 'CloudFunctionsServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py new file mode 100644 index 0000000..3010041 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py @@ -0,0 +1,1423 @@ +# -*- 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_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.functions_v1.services.cloud_functions_service import pagers +from google.cloud.functions_v1.types import functions +from google.cloud.functions_v1.types import operations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport +from .client import CloudFunctionsServiceClient + + +class CloudFunctionsServiceAsyncClient: + """A service that application uses to manipulate triggers and + functions. + """ + + _client: CloudFunctionsServiceClient + + DEFAULT_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT + + cloud_function_path = staticmethod(CloudFunctionsServiceClient.cloud_function_path) + parse_cloud_function_path = staticmethod(CloudFunctionsServiceClient.parse_cloud_function_path) + crypto_key_path = staticmethod(CloudFunctionsServiceClient.crypto_key_path) + parse_crypto_key_path = staticmethod(CloudFunctionsServiceClient.parse_crypto_key_path) + repository_path = staticmethod(CloudFunctionsServiceClient.repository_path) + parse_repository_path = staticmethod(CloudFunctionsServiceClient.parse_repository_path) + common_billing_account_path = staticmethod(CloudFunctionsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CloudFunctionsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CloudFunctionsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CloudFunctionsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CloudFunctionsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CloudFunctionsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CloudFunctionsServiceClient.common_project_path) + parse_common_project_path = staticmethod(CloudFunctionsServiceClient.parse_common_project_path) + common_location_path = staticmethod(CloudFunctionsServiceClient.common_location_path) + parse_common_location_path = staticmethod(CloudFunctionsServiceClient.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: + CloudFunctionsServiceAsyncClient: The constructed client. + """ + return CloudFunctionsServiceClient.from_service_account_info.__func__(CloudFunctionsServiceAsyncClient, 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: + CloudFunctionsServiceAsyncClient: The constructed client. + """ + return CloudFunctionsServiceClient.from_service_account_file.__func__(CloudFunctionsServiceAsyncClient, 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 CloudFunctionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CloudFunctionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CloudFunctionsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CloudFunctionsServiceClient).get_transport_class, type(CloudFunctionsServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CloudFunctionsServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud functions service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CloudFunctionsServiceTransport]): 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 = CloudFunctionsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_functions(self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsAsyncPager: + r"""Returns a list of functions that belong to the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): + The request object. Request for the `ListFunctions` + 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager: + Response for the ListFunctions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = functions.ListFunctionsRequest(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.list_functions, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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.ListFunctionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_function(self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CloudFunction: + r"""Returns a function with the given name from the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): + The request object. Request for the `GetFunction` + method. + name (:class:`str`): + Required. The name of the function + which details should be obtained. + + 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.functions_v1.types.CloudFunction: + Describes a Cloud Function that + contains user computation executed in + response to an event. It encapsulate + function and triggers configurations. + + """ + # 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 = functions.GetFunctionRequest(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_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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 create_function(self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + location: str = None, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): + The request object. Request for the `CreateFunction` + method. + location (:class:`str`): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``location`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function (:class:`google.cloud.functions_v1.types.CloudFunction`): + Required. Function to be created. + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([location, function]) + if request is 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 = functions.CreateFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if location is not None: + request.location = location + if function is not None: + request.function = function + + # 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_function, + default_timeout=600.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(( + ("location", request.location), + )), + ) + + # 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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def update_function(self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates existing function. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): + The request object. Request for the `UpdateFunction` + method. + function (:class:`google.cloud.functions_v1.types.CloudFunction`): + Required. New version of the + function. + + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([function]) + if request is 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 = functions.UpdateFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if function is not None: + request.function = function + + # 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_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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(( + ("function.name", request.function.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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def delete_function(self, + request: Union[functions.DeleteFunctionRequest, 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 function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): + The request object. Request for the `DeleteFunction` + method. + name (:class:`str`): + Required. The name of the function + which should be deleted. + + 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.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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 = functions.DeleteFunctionRequest(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_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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, + empty_pb2.Empty, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def call_function(self, + request: Union[functions.CallFunctionRequest, dict] = None, + *, + name: str = None, + data: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CallFunctionResponse: + r"""Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = await client.call_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): + The request object. Request for the `CallFunction` + method. + name (:class:`str`): + Required. The name of the function to + be called. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (:class:`str`): + Required. Input to be passed to the + function. + + This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: + Response of CallFunction method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, data]) + if request is 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 = functions.CallFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.call_function, + default_timeout=600.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 generate_upload_url(self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: + r"""Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = await client.generate_upload_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): + The request object. Request of `GenerateSourceUploadUrl` + 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.cloud.functions_v1.types.GenerateUploadUrlResponse: + Response of GenerateSourceUploadUrl method. + """ + # Create or coerce a protobuf request object. + request = functions.GenerateUploadUrlRequest(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.generate_upload_url, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_download_url(self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: + r"""Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = await client.generate_download_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): + The request object. Request of `GenerateDownloadUrl` + 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: + Response of GenerateDownloadUrl method. + """ + # Create or coerce a protobuf request object. + request = functions.GenerateDownloadUrlRequest(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.generate_download_url, + 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 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 on the specified + function. Replaces any existing policy. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await 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 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"""Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await 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 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"""Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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) + + 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-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CloudFunctionsServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py new file mode 100644 index 0000000..53c6f1a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py @@ -0,0 +1,1613 @@ +# -*- 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_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.functions_v1.services.cloud_functions_service import pagers +from google.cloud.functions_v1.types import functions +from google.cloud.functions_v1.types import operations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CloudFunctionsServiceGrpcTransport +from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport + + +class CloudFunctionsServiceClientMeta(type): + """Metaclass for the CloudFunctionsService 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[CloudFunctionsServiceTransport]] + _transport_registry["grpc"] = CloudFunctionsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CloudFunctionsServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CloudFunctionsServiceTransport]: + """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 CloudFunctionsServiceClient(metaclass=CloudFunctionsServiceClientMeta): + """A service that application uses to manipulate triggers and + functions. + """ + + @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 = "cloudfunctions.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: + CloudFunctionsServiceClient: 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: + CloudFunctionsServiceClient: 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) -> CloudFunctionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CloudFunctionsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def cloud_function_path(project: str,location: str,function: str,) -> str: + """Returns a fully-qualified cloud_function string.""" + return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + + @staticmethod + def parse_cloud_function_path(path: str) -> Dict[str,str]: + """Parses a cloud_function path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?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 repository_path(project: str,location: str,repository: str,) -> str: + """Returns a fully-qualified repository string.""" + return "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) + + @staticmethod + def parse_repository_path(path: str) -> Dict[str,str]: + """Parses a repository path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/repositories/(?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, CloudFunctionsServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud functions service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CloudFunctionsServiceTransport]): 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, CloudFunctionsServiceTransport): + # transport is a CloudFunctionsServiceTransport 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, + api_audience=client_options.api_audience, + ) + + def list_functions(self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsPager: + r"""Returns a list of functions that belong to the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): + The request object. Request for the `ListFunctions` + 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager: + Response for the ListFunctions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.ListFunctionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.ListFunctionsRequest): + request = functions.ListFunctionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_functions] + + # 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.ListFunctionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_function(self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CloudFunction: + r"""Returns a function with the given name from the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = client.get_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): + The request object. Request for the `GetFunction` + method. + name (str): + Required. The name of the function + which details should be obtained. + + 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.functions_v1.types.CloudFunction: + Describes a Cloud Function that + contains user computation executed in + response to an event. It encapsulate + function and triggers configurations. + + """ + # 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 functions.GetFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GetFunctionRequest): + request = functions.GetFunctionRequest(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_function] + + # 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 create_function(self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + location: str = None, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): + The request object. Request for the `CreateFunction` + method. + location (str): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``location`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function (google.cloud.functions_v1.types.CloudFunction): + Required. Function to be created. + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([location, function]) + if request is 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 functions.CreateFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.CreateFunctionRequest): + request = functions.CreateFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if location is not None: + request.location = location + if function is not None: + request.function = function + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("location", request.location), + )), + ) + + # 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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def update_function(self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates existing function. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): + The request object. Request for the `UpdateFunction` + method. + function (google.cloud.functions_v1.types.CloudFunction): + Required. New version of the + function. + + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([function]) + if request is 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 functions.UpdateFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.UpdateFunctionRequest): + request = functions.UpdateFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if function is not None: + request.function = function + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("function.name", request.function.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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def delete_function(self, + request: Union[functions.DeleteFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): + The request object. Request for the `DeleteFunction` + method. + name (str): + Required. The name of the function + which should be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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 functions.DeleteFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.DeleteFunctionRequest): + request = functions.DeleteFunctionRequest(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_function] + + # 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, + empty_pb2.Empty, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def call_function(self, + request: Union[functions.CallFunctionRequest, dict] = None, + *, + name: str = None, + data: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CallFunctionResponse: + r"""Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = client.call_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): + The request object. Request for the `CallFunction` + method. + name (str): + Required. The name of the function to + be called. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (str): + Required. Input to be passed to the + function. + + This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: + Response of CallFunction method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, data]) + if request is 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 functions.CallFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.CallFunctionRequest): + request = functions.CallFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.call_function] + + # 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 generate_upload_url(self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: + r"""Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = client.generate_upload_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): + The request object. Request of `GenerateSourceUploadUrl` + 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.cloud.functions_v1.types.GenerateUploadUrlResponse: + Response of GenerateSourceUploadUrl method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.GenerateUploadUrlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GenerateUploadUrlRequest): + request = functions.GenerateUploadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_upload_url] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_download_url(self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: + r"""Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = client.generate_download_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): + The request object. Request of `GenerateDownloadUrl` + 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: + Response of GenerateDownloadUrl method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.GenerateDownloadUrlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GenerateDownloadUrlRequest): + request = functions.GenerateDownloadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_download_url] + + # 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 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 on the specified + function. Replaces any existing policy. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 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"""Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 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"""Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CloudFunctionsServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py new file mode 100644 index 0000000..f31d4f1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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.functions_v1.types import functions + + +class ListFunctionsPager: + """A pager for iterating through ``list_functions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``functions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFunctions`` requests and continue to iterate + through the ``functions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` + 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[..., functions.ListFunctionsResponse], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + 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.functions_v1.types.ListFunctionsRequest): + The initial request object. + response (google.cloud.functions_v1.types.ListFunctionsResponse): + 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 = functions.ListFunctionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[functions.ListFunctionsResponse]: + 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[functions.CloudFunction]: + for page in self.pages: + yield from page.functions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFunctionsAsyncPager: + """A pager for iterating through ``list_functions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``functions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFunctions`` requests and continue to iterate + through the ``functions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` + 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[functions.ListFunctionsResponse]], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + 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.functions_v1.types.ListFunctionsRequest): + The initial request object. + response (google.cloud.functions_v1.types.ListFunctionsResponse): + 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 = functions.ListFunctionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[functions.ListFunctionsResponse]: + 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[functions.CloudFunction]: + async def async_generator(): + async for page in self.pages: + for response in page.functions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py new file mode 100644 index 0000000..ac1ba7e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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 CloudFunctionsServiceTransport +from .grpc import CloudFunctionsServiceGrpcTransport +from .grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CloudFunctionsServiceTransport]] +_transport_registry['grpc'] = CloudFunctionsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CloudFunctionsServiceGrpcAsyncIOTransport + +__all__ = ( + 'CloudFunctionsServiceTransport', + 'CloudFunctionsServiceGrpcTransport', + 'CloudFunctionsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py new file mode 100644 index 0000000..2d3352f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py @@ -0,0 +1,331 @@ +# -*- 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.functions_v1.types import functions +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-functions', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CloudFunctionsServiceTransport(abc.ABC): + """Abstract transport class for CloudFunctionsService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'cloudfunctions.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, + api_audience: Optional[str] = None, + **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. + """ + + 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) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_functions: gapic_v1.method.wrap_method( + self.list_functions, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_function: gapic_v1.method.wrap_method( + self.get_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.create_function: gapic_v1.method.wrap_method( + self.create_function, + default_timeout=600.0, + client_info=client_info, + ), + self.update_function: gapic_v1.method.wrap_method( + self.update_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_function: gapic_v1.method.wrap_method( + self.delete_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.call_function: gapic_v1.method.wrap_method( + self.call_function, + default_timeout=600.0, + client_info=client_info, + ), + self.generate_upload_url: gapic_v1.method.wrap_method( + self.generate_upload_url, + default_timeout=None, + client_info=client_info, + ), + self.generate_download_url: gapic_v1.method.wrap_method( + self.generate_download_url, + 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.get_iam_policy: gapic_v1.method.wrap_method( + self.get_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 list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + Union[ + functions.ListFunctionsResponse, + Awaitable[functions.ListFunctionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_function(self) -> Callable[ + [functions.GetFunctionRequest], + Union[ + functions.CloudFunction, + Awaitable[functions.CloudFunction] + ]]: + raise NotImplementedError() + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def call_function(self) -> Callable[ + [functions.CallFunctionRequest], + Union[ + functions.CallFunctionResponse, + Awaitable[functions.CallFunctionResponse] + ]]: + raise NotImplementedError() + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + Union[ + functions.GenerateUploadUrlResponse, + Awaitable[functions.GenerateUploadUrlResponse] + ]]: + raise NotImplementedError() + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Union[ + functions.GenerateDownloadUrlResponse, + Awaitable[functions.GenerateDownloadUrlResponse] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CloudFunctionsServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py new file mode 100644 index 0000000..92c02c9 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py @@ -0,0 +1,593 @@ +# -*- 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.functions_v1.types import functions +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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO + + +class CloudFunctionsServiceGrpcTransport(CloudFunctionsServiceTransport): + """gRPC backend transport for CloudFunctionsService. + + A service that application uses to manipulate triggers and + functions. + + 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 = 'cloudfunctions.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, + api_audience: Optional[str] = None, + ) -> 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, + api_audience=api_audience, + ) + + 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 = 'cloudfunctions.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 list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + functions.ListFunctionsResponse]: + r"""Return a callable for the list functions method over gRPC. + + Returns a list of functions that belong to the + requested project. + + Returns: + Callable[[~.ListFunctionsRequest], + ~.ListFunctionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_functions' not in self._stubs: + self._stubs['list_functions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', + request_serializer=functions.ListFunctionsRequest.serialize, + response_deserializer=functions.ListFunctionsResponse.deserialize, + ) + return self._stubs['list_functions'] + + @property + def get_function(self) -> Callable[ + [functions.GetFunctionRequest], + functions.CloudFunction]: + r"""Return a callable for the get function method over gRPC. + + Returns a function with the given name from the + requested project. + + Returns: + Callable[[~.GetFunctionRequest], + ~.CloudFunction]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_function' not in self._stubs: + self._stubs['get_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', + request_serializer=functions.GetFunctionRequest.serialize, + response_deserializer=functions.CloudFunction.deserialize, + ) + return self._stubs['get_function'] + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create function method over gRPC. + + Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + Returns: + Callable[[~.CreateFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['create_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', + request_serializer=functions.CreateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_function'] + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the update function method over gRPC. + + Updates existing function. + + Returns: + Callable[[~.UpdateFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['update_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', + request_serializer=functions.UpdateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_function'] + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete function method over gRPC. + + Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + Returns: + Callable[[~.DeleteFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['delete_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', + request_serializer=functions.DeleteFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_function'] + + @property + def call_function(self) -> Callable[ + [functions.CallFunctionRequest], + functions.CallFunctionResponse]: + r"""Return a callable for the call function method over gRPC. + + Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + Returns: + Callable[[~.CallFunctionRequest], + ~.CallFunctionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'call_function' not in self._stubs: + self._stubs['call_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', + request_serializer=functions.CallFunctionRequest.serialize, + response_deserializer=functions.CallFunctionResponse.deserialize, + ) + return self._stubs['call_function'] + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + functions.GenerateUploadUrlResponse]: + r"""Return a callable for the generate upload url method over gRPC. + + Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + Returns: + Callable[[~.GenerateUploadUrlRequest], + ~.GenerateUploadUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_upload_url' not in self._stubs: + self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', + request_serializer=functions.GenerateUploadUrlRequest.serialize, + response_deserializer=functions.GenerateUploadUrlResponse.deserialize, + ) + return self._stubs['generate_upload_url'] + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + functions.GenerateDownloadUrlResponse]: + r"""Return a callable for the generate download url method over gRPC. + + Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + Returns: + Callable[[~.GenerateDownloadUrlRequest], + ~.GenerateDownloadUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_download_url' not in self._stubs: + self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', + request_serializer=functions.GenerateDownloadUrlRequest.serialize, + response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, + ) + return self._stubs['generate_download_url'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/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__ = ( + 'CloudFunctionsServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..d05047d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py @@ -0,0 +1,592 @@ +# -*- 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.functions_v1.types import functions +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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CloudFunctionsServiceGrpcTransport + + +class CloudFunctionsServiceGrpcAsyncIOTransport(CloudFunctionsServiceTransport): + """gRPC AsyncIO backend transport for CloudFunctionsService. + + A service that application uses to manipulate triggers and + functions. + + 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 = 'cloudfunctions.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 = 'cloudfunctions.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, + api_audience: Optional[str] = None, + ) -> 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, + api_audience=api_audience, + ) + + 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 list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + Awaitable[functions.ListFunctionsResponse]]: + r"""Return a callable for the list functions method over gRPC. + + Returns a list of functions that belong to the + requested project. + + Returns: + Callable[[~.ListFunctionsRequest], + Awaitable[~.ListFunctionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_functions' not in self._stubs: + self._stubs['list_functions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', + request_serializer=functions.ListFunctionsRequest.serialize, + response_deserializer=functions.ListFunctionsResponse.deserialize, + ) + return self._stubs['list_functions'] + + @property + def get_function(self) -> Callable[ + [functions.GetFunctionRequest], + Awaitable[functions.CloudFunction]]: + r"""Return a callable for the get function method over gRPC. + + Returns a function with the given name from the + requested project. + + Returns: + Callable[[~.GetFunctionRequest], + Awaitable[~.CloudFunction]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_function' not in self._stubs: + self._stubs['get_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', + request_serializer=functions.GetFunctionRequest.serialize, + response_deserializer=functions.CloudFunction.deserialize, + ) + return self._stubs['get_function'] + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create function method over gRPC. + + Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + Returns: + Callable[[~.CreateFunctionRequest], + 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_function' not in self._stubs: + self._stubs['create_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', + request_serializer=functions.CreateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_function'] + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update function method over gRPC. + + Updates existing function. + + Returns: + Callable[[~.UpdateFunctionRequest], + 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_function' not in self._stubs: + self._stubs['update_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', + request_serializer=functions.UpdateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_function'] + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete function method over gRPC. + + Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + Returns: + Callable[[~.DeleteFunctionRequest], + 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_function' not in self._stubs: + self._stubs['delete_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', + request_serializer=functions.DeleteFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_function'] + + @property + def call_function(self) -> Callable[ + [functions.CallFunctionRequest], + Awaitable[functions.CallFunctionResponse]]: + r"""Return a callable for the call function method over gRPC. + + Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + Returns: + Callable[[~.CallFunctionRequest], + Awaitable[~.CallFunctionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'call_function' not in self._stubs: + self._stubs['call_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', + request_serializer=functions.CallFunctionRequest.serialize, + response_deserializer=functions.CallFunctionResponse.deserialize, + ) + return self._stubs['call_function'] + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + Awaitable[functions.GenerateUploadUrlResponse]]: + r"""Return a callable for the generate upload url method over gRPC. + + Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + Returns: + Callable[[~.GenerateUploadUrlRequest], + Awaitable[~.GenerateUploadUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_upload_url' not in self._stubs: + self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', + request_serializer=functions.GenerateUploadUrlRequest.serialize, + response_deserializer=functions.GenerateUploadUrlResponse.deserialize, + ) + return self._stubs['generate_upload_url'] + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Awaitable[functions.GenerateDownloadUrlResponse]]: + r"""Return a callable for the generate download url method over gRPC. + + Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + Returns: + Callable[[~.GenerateDownloadUrlRequest], + Awaitable[~.GenerateDownloadUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_download_url' not in self._stubs: + self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', + request_serializer=functions.GenerateDownloadUrlRequest.serialize, + response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, + ) + return self._stubs['generate_download_url'] + + @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 on the specified + function. Replaces 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.functions.v1.CloudFunctionsService/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + 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.functions.v1.CloudFunctionsService/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Returns: + Callable[[~.TestIamPermissionsRequest], + 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.functions.v1.CloudFunctionsService/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__ = ( + 'CloudFunctionsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py new file mode 100644 index 0000000..b09e206 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py @@ -0,0 +1,66 @@ +# -*- 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 .functions import ( + CallFunctionRequest, + CallFunctionResponse, + CloudFunction, + CreateFunctionRequest, + DeleteFunctionRequest, + EventTrigger, + FailurePolicy, + GenerateDownloadUrlRequest, + GenerateDownloadUrlResponse, + GenerateUploadUrlRequest, + GenerateUploadUrlResponse, + GetFunctionRequest, + HttpsTrigger, + ListFunctionsRequest, + ListFunctionsResponse, + SecretEnvVar, + SecretVolume, + SourceRepository, + UpdateFunctionRequest, + CloudFunctionStatus, +) +from .operations import ( + OperationMetadataV1, + OperationType, +) + +__all__ = ( + 'CallFunctionRequest', + 'CallFunctionResponse', + 'CloudFunction', + 'CreateFunctionRequest', + 'DeleteFunctionRequest', + 'EventTrigger', + 'FailurePolicy', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GetFunctionRequest', + 'HttpsTrigger', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'SecretEnvVar', + 'SecretVolume', + 'SourceRepository', + 'UpdateFunctionRequest', + 'CloudFunctionStatus', + 'OperationMetadataV1', + 'OperationType', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py new file mode 100644 index 0000000..844c961 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py @@ -0,0 +1,1067 @@ +# -*- 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 duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.functions.v1', + manifest={ + 'CloudFunctionStatus', + 'CloudFunction', + 'SourceRepository', + 'HttpsTrigger', + 'EventTrigger', + 'FailurePolicy', + 'SecretEnvVar', + 'SecretVolume', + 'CreateFunctionRequest', + 'UpdateFunctionRequest', + 'GetFunctionRequest', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'DeleteFunctionRequest', + 'CallFunctionRequest', + 'CallFunctionResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + }, +) + + +class CloudFunctionStatus(proto.Enum): + r"""Describes the current stage of a deployment.""" + CLOUD_FUNCTION_STATUS_UNSPECIFIED = 0 + ACTIVE = 1 + OFFLINE = 2 + DEPLOY_IN_PROGRESS = 3 + DELETE_IN_PROGRESS = 4 + UNKNOWN = 5 + + +class CloudFunction(proto.Message): + r"""Describes a Cloud Function that contains user computation + executed in response to an event. It encapsulate function and + triggers configurations. + + 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): + A user-defined name of the function. Function names must be + unique globally and match pattern + ``projects/*/locations/*/functions/*`` + description (str): + User-provided description of a function. + source_archive_url (str): + The Google Cloud Storage URL, starting with ``gs://``, + pointing to the zip archive which contains the function. + + This field is a member of `oneof`_ ``source_code``. + source_repository (google.cloud.functions_v1.types.SourceRepository): + **Beta Feature** + + The source repository where a function is hosted. + + This field is a member of `oneof`_ ``source_code``. + source_upload_url (str): + The Google Cloud Storage signed URL used for source + uploading, generated by calling + [google.cloud.functions.v1.GenerateUploadUrl]. + + The signature is validated on write methods (Create, Update) + The signature is stripped from the Function object on read + methods (Get, List) + + This field is a member of `oneof`_ ``source_code``. + https_trigger (google.cloud.functions_v1.types.HttpsTrigger): + An HTTPS endpoint type of source that can be + triggered via URL. + + This field is a member of `oneof`_ ``trigger``. + event_trigger (google.cloud.functions_v1.types.EventTrigger): + A source that fires events in response to a + condition in another service. + + This field is a member of `oneof`_ ``trigger``. + status (google.cloud.functions_v1.types.CloudFunctionStatus): + Output only. Status of the function + deployment. + entry_point (str): + The name of the function (as defined in source code) that + will be executed. Defaults to the resource name suffix, if + not specified. For backward compatibility, if function with + given name is not found, then the system will try to use + function named "function". For Node.js this is name of a + function exported by the module specified in + ``source_location``. + runtime (str): + The runtime in which to run the function. Required when + deploying a new function, optional when updating an existing + function. For a complete list of possible choices, see the + ```gcloud`` command + reference `__. + timeout (google.protobuf.duration_pb2.Duration): + The function execution timeout. Execution is + considered failed and can be terminated if the + function is not completed at the end of the + timeout period. Defaults to 60 seconds. + available_memory_mb (int): + The amount of memory in MB available for a + function. Defaults to 256MB. + service_account_email (str): + The email of the function's service account. If empty, + defaults to ``{project_id}@appspot.gserviceaccount.com``. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update timestamp of a + Cloud Function. + version_id (int): + Output only. The version identifier of the + Cloud Function. Each deployment attempt results + in a new version of a function being created. + labels (Mapping[str, str]): + Labels associated with this Cloud Function. + environment_variables (Mapping[str, str]): + Environment variables that shall be available + during function execution. + build_environment_variables (Mapping[str, str]): + Build environment variables that shall be + available during build time. + network (str): + The VPC Network that this cloud function can connect to. It + can be either the fully-qualified URI, or the short name of + the network resource. If the short network name is used, the + network must belong to the same project. Otherwise, it must + belong to a project within the same organization. The format + of this field is either + ``projects/{project}/global/networks/{network}`` or + ``{network}``, where ``{project}`` is a project id where the + network is defined, and ``{network}`` is the short name of + the network. + + This field is mutually exclusive with ``vpc_connector`` and + will be replaced by it. + + See `the VPC + documentation `__ + for more information on connecting Cloud projects. + max_instances (int): + The limit on the maximum number of function instances that + may coexist at a given time. + + In some cases, such as rapid traffic surges, Cloud Functions + may, for a short period of time, create more instances than + the specified max instances limit. If your function cannot + tolerate this temporary behavior, you may want to factor in + a safety margin and set a lower max instances value than + your function can tolerate. + + See the `Max + Instances `__ + Guide for more details. + min_instances (int): + A lower bound for the number function + instances that may coexist at a given time. + vpc_connector (str): + The VPC Network Connector that this cloud function can + connect to. It can be either the fully-qualified URI, or the + short name of the network connector resource. The format of + this field is ``projects/*/locations/*/connectors/*`` + + This field is mutually exclusive with ``network`` field and + will eventually replace it. + + See `the VPC + documentation `__ + for more information on connecting Cloud projects. + vpc_connector_egress_settings (google.cloud.functions_v1.types.CloudFunction.VpcConnectorEgressSettings): + The egress settings for the connector, + controlling what traffic is diverted through it. + ingress_settings (google.cloud.functions_v1.types.CloudFunction.IngressSettings): + The ingress settings for the function, + controlling what traffic can reach it. + kms_key_name (str): + Resource name of a KMS crypto key (managed by the user) used + to encrypt/decrypt function resources. + + It must match the pattern + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. + + If specified, you must also provide an artifact registry + repository using the ``docker_repository`` field that was + created with the same KMS crypto key. + + The following service accounts need to be granted the role + 'Cloud KMS CryptoKey Encrypter/Decrypter + (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the + Key/KeyRing/Project/Organization (least access preferred). + + 1. Google Cloud Functions service account + (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) + - Required to protect the function's image. + 2. Google Storage service account + (service-{project_number}@gs-project-accounts.iam.gserviceaccount.com) + - Required to protect the function's source code. If this + service account does not exist, deploying a function + without a KMS key or retrieving the service agent name + provisions it. For more information, see + https://cloud.google.com/storage/docs/projects#service-agents + and + https://cloud.google.com/storage/docs/getting-service-agent#gsutil. + + Google Cloud Functions delegates access to service agents to + protect function resources in internal projects that are not + accessible by the end user. + build_worker_pool (str): + Name of the Cloud Build Custom Worker Pool that should be + used to build the function. The format of this field is + ``projects/{project}/locations/{region}/workerPools/{workerPool}`` + where ``{project}`` and ``{region}`` are the project id and + region respectively where the worker pool is defined and + ``{workerPool}`` is the short name of the worker pool. + + If the project id is not the same as the function, then the + Cloud Functions Service Agent + (``service-@gcf-admin-robot.iam.gserviceaccount.com``) + must be granted the role Cloud Build Custom Workers Builder + (``roles/cloudbuild.customworkers.builder``) in the project. + build_id (str): + Output only. The Cloud Build ID of the latest + successful deployment of the function. + build_name (str): + Output only. The Cloud Build Name of the function + deployment. + ``projects//locations//builds/``. + secret_environment_variables (Sequence[google.cloud.functions_v1.types.SecretEnvVar]): + Secret environment variables configuration. + secret_volumes (Sequence[google.cloud.functions_v1.types.SecretVolume]): + Secret volumes configuration. + source_token (str): + Input only. An identifier for Firebase + function sources. Disclaimer: This field is only + supported for Firebase function deployments. + docker_repository (str): + User managed repository created in Artifact Registry + optionally with a customer managed encryption key. If + specified, deployments will use Artifact Registry. If + unspecified and the deployment is eligible to use Artifact + Registry, GCF will create and use a repository named + 'gcf-artifacts' for every deployed region. This is the + repository to which the function docker image will be pushed + after it is built by Cloud Build. + + It must match the pattern + ``projects/{project}/locations/{location}/repositories/{repository}``. + + Cross-project repositories are not supported. Cross-location + repositories are not supported. Repository format must be + 'DOCKER'. + docker_registry (google.cloud.functions_v1.types.CloudFunction.DockerRegistry): + Docker Registry to use for this deployment. + + If ``docker_repository`` field is specified, this field will + be automatically set as ``ARTIFACT_REGISTRY``. If + unspecified, it currently defaults to + ``CONTAINER_REGISTRY``. This field may be overridden by the + backend for eligible deployments. + """ + class VpcConnectorEgressSettings(proto.Enum): + r"""Available egress settings. + + This controls what traffic is diverted through the VPC Access + Connector resource. By default PRIVATE_RANGES_ONLY will be used. + """ + VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED = 0 + PRIVATE_RANGES_ONLY = 1 + ALL_TRAFFIC = 2 + + class IngressSettings(proto.Enum): + r"""Available ingress settings. + + This controls what traffic can reach the function. + + If unspecified, ALLOW_ALL will be used. + """ + INGRESS_SETTINGS_UNSPECIFIED = 0 + ALLOW_ALL = 1 + ALLOW_INTERNAL_ONLY = 2 + ALLOW_INTERNAL_AND_GCLB = 3 + + class DockerRegistry(proto.Enum): + r"""Docker Registry to use for storing function Docker images.""" + DOCKER_REGISTRY_UNSPECIFIED = 0 + CONTAINER_REGISTRY = 1 + ARTIFACT_REGISTRY = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + source_archive_url = proto.Field( + proto.STRING, + number=3, + oneof='source_code', + ) + source_repository = proto.Field( + proto.MESSAGE, + number=4, + oneof='source_code', + message='SourceRepository', + ) + source_upload_url = proto.Field( + proto.STRING, + number=16, + oneof='source_code', + ) + https_trigger = proto.Field( + proto.MESSAGE, + number=5, + oneof='trigger', + message='HttpsTrigger', + ) + event_trigger = proto.Field( + proto.MESSAGE, + number=6, + oneof='trigger', + message='EventTrigger', + ) + status = proto.Field( + proto.ENUM, + number=7, + enum='CloudFunctionStatus', + ) + entry_point = proto.Field( + proto.STRING, + number=8, + ) + runtime = proto.Field( + proto.STRING, + number=19, + ) + timeout = proto.Field( + proto.MESSAGE, + number=9, + message=duration_pb2.Duration, + ) + available_memory_mb = proto.Field( + proto.INT32, + number=10, + ) + service_account_email = proto.Field( + proto.STRING, + number=11, + ) + update_time = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + version_id = proto.Field( + proto.INT64, + number=14, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=15, + ) + environment_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=17, + ) + build_environment_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=28, + ) + network = proto.Field( + proto.STRING, + number=18, + ) + max_instances = proto.Field( + proto.INT32, + number=20, + ) + min_instances = proto.Field( + proto.INT32, + number=32, + ) + vpc_connector = proto.Field( + proto.STRING, + number=22, + ) + vpc_connector_egress_settings = proto.Field( + proto.ENUM, + number=23, + enum=VpcConnectorEgressSettings, + ) + ingress_settings = proto.Field( + proto.ENUM, + number=24, + enum=IngressSettings, + ) + kms_key_name = proto.Field( + proto.STRING, + number=25, + ) + build_worker_pool = proto.Field( + proto.STRING, + number=26, + ) + build_id = proto.Field( + proto.STRING, + number=27, + ) + build_name = proto.Field( + proto.STRING, + number=33, + ) + secret_environment_variables = proto.RepeatedField( + proto.MESSAGE, + number=29, + message='SecretEnvVar', + ) + secret_volumes = proto.RepeatedField( + proto.MESSAGE, + number=30, + message='SecretVolume', + ) + source_token = proto.Field( + proto.STRING, + number=31, + ) + docker_repository = proto.Field( + proto.STRING, + number=34, + ) + docker_registry = proto.Field( + proto.ENUM, + number=35, + enum=DockerRegistry, + ) + + +class SourceRepository(proto.Message): + r"""Describes SourceRepository, used to represent parameters + related to source repository where a function is hosted. + + Attributes: + url (str): + The URL pointing to the hosted repository where the function + is defined. There are supported Cloud Source Repository URLs + in the following formats: + + To refer to a specific commit: + ``https://source.developers.google.com/projects/*/repos/*/revisions/*/paths/*`` + To refer to a moveable alias (branch): + ``https://source.developers.google.com/projects/*/repos/*/moveable-aliases/*/paths/*`` + In particular, to refer to HEAD use ``master`` moveable + alias. To refer to a specific fixed alias (tag): + ``https://source.developers.google.com/projects/*/repos/*/fixed-aliases/*/paths/*`` + + You may omit ``paths/*`` if you want to use the main + directory. + deployed_url (str): + Output only. The URL pointing to the hosted + repository where the function were defined at + the time of deployment. It always points to a + specific commit in the format described above. + """ + + url = proto.Field( + proto.STRING, + number=1, + ) + deployed_url = proto.Field( + proto.STRING, + number=2, + ) + + +class HttpsTrigger(proto.Message): + r"""Describes HttpsTrigger, could be used to connect web hooks to + function. + + Attributes: + url (str): + Output only. The deployed url for the + function. + security_level (google.cloud.functions_v1.types.HttpsTrigger.SecurityLevel): + The security level for the function. + """ + class SecurityLevel(proto.Enum): + r"""Available security level settings. + + This controls the methods to enforce security (HTTPS) on a URL. + + If unspecified, SECURE_OPTIONAL will be used. + """ + SECURITY_LEVEL_UNSPECIFIED = 0 + SECURE_ALWAYS = 1 + SECURE_OPTIONAL = 2 + + url = proto.Field( + proto.STRING, + number=1, + ) + security_level = proto.Field( + proto.ENUM, + number=2, + enum=SecurityLevel, + ) + + +class EventTrigger(proto.Message): + r"""Describes EventTrigger, used to request events be sent from + another service. + + Attributes: + event_type (str): + Required. The type of event to observe. For example: + ``providers/cloud.storage/eventTypes/object.change`` and + ``providers/cloud.pubsub/eventTypes/topic.publish``. + + Event types match pattern ``providers/*/eventTypes/*.*``. + The pattern contains: + + 1. namespace: For example, ``cloud.storage`` and + ``google.firebase.analytics``. + 2. resource type: The type of resource on which event + occurs. For example, the Google Cloud Storage API + includes the type ``object``. + 3. action: The action that generates the event. For example, + action for a Google Cloud Storage Object is 'change'. + These parts are lower case. + resource (str): + Required. The resource(s) from which to observe events, for + example, ``projects/_/buckets/myBucket``. + + Not all syntactically correct values are accepted by all + services. For example: + + 1. The authorization model must support it. Google Cloud + Functions only allows EventTriggers to be deployed that + observe resources in the same project as the + ``CloudFunction``. + 2. The resource type must match the pattern expected for an + ``event_type``. For example, an ``EventTrigger`` that has + an ``event_type`` of "google.pubsub.topic.publish" should + have a resource that matches Google Cloud Pub/Sub topics. + + Additionally, some services may support short names when + creating an ``EventTrigger``. These will always be returned + in the normalized "long" format. + + See each *service's* documentation for supported formats. + service (str): + The hostname of the service that should be observed. + + If no string is provided, the default service implementing + the API will be used. For example, + ``storage.googleapis.com`` is the default for all event + types in the ``google.storage`` namespace. + failure_policy (google.cloud.functions_v1.types.FailurePolicy): + Specifies policy for failed executions. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + resource = proto.Field( + proto.STRING, + number=2, + ) + service = proto.Field( + proto.STRING, + number=3, + ) + failure_policy = proto.Field( + proto.MESSAGE, + number=5, + message='FailurePolicy', + ) + + +class FailurePolicy(proto.Message): + r"""Describes the policy in case of function's execution failure. + If empty, then defaults to ignoring failures (i.e. not retrying + them). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + retry (google.cloud.functions_v1.types.FailurePolicy.Retry): + If specified, then the function will be + retried in case of a failure. + + This field is a member of `oneof`_ ``action``. + """ + + class Retry(proto.Message): + r"""Describes the retry policy in case of function's execution + failure. A function execution will be retried on any failure. A + failed execution will be retried up to 7 days with an + exponential backoff (capped at 10 seconds). + Retried execution is charged as any other execution. + + """ + + retry = proto.Field( + proto.MESSAGE, + number=1, + oneof='action', + message=Retry, + ) + + +class SecretEnvVar(proto.Message): + r"""Configuration for a secret environment variable. It has the + information necessary to fetch the secret value from secret + manager and expose it as an environment variable. + + Attributes: + key (str): + Name of the environment variable. + project_id (str): + Project identifier (preferrably project + number but can also be the project ID) of the + project that contains the secret. If not set, it + will be populated with the function's project + assuming that the secret exists in the same + project as of the function. + secret (str): + Name of the secret in secret manager (not the + full resource name). + version (str): + Version of the secret (version number or the + string 'latest'). It is recommended to use a + numeric version for secret environment variables + as any updates to the secret value is not + reflected until new instances start. + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + secret = proto.Field( + proto.STRING, + number=3, + ) + version = proto.Field( + proto.STRING, + number=4, + ) + + +class SecretVolume(proto.Message): + r"""Configuration for a secret volume. It has the information + necessary to fetch the secret value from secret manager and make + it available as files mounted at the requested paths within the + application container. Secret value is not a part of the + configuration. Every filesystem read operation performs a lookup + in secret manager to retrieve the secret value. + + Attributes: + mount_path (str): + The path within the container to mount the secret volume. + For example, setting the mount_path as ``/etc/secrets`` + would mount the secret value files under the + ``/etc/secrets`` directory. This directory will also be + completely shadowed and unavailable to mount any other + secrets. + + Recommended mount paths: /etc/secrets Restricted mount + paths: /cloudsql, /dev/log, /pod, /proc, /var/log + project_id (str): + Project identifier (preferrably project + number but can also be the project ID) of the + project that contains the secret. If not set, it + will be populated with the function's project + assuming that the secret exists in the same + project as of the function. + secret (str): + Name of the secret in secret manager (not the + full resource name). + versions (Sequence[google.cloud.functions_v1.types.SecretVolume.SecretVersion]): + List of secret versions to mount for this secret. If empty, + the ``latest`` version of the secret will be made available + in a file named after the secret under the mount point. + """ + + class SecretVersion(proto.Message): + r"""Configuration for a single version. + + Attributes: + version (str): + Version of the secret (version number or the string + 'latest'). It is preferrable to use ``latest`` version with + secret volumes as secret value changes are reflected + immediately. + path (str): + Relative path of the file under the mount path where the + secret value for this version will be fetched and made + available. For example, setting the mount_path as + '/etc/secrets' and path as ``/secret_foo`` would mount the + secret value file at ``/etc/secrets/secret_foo``. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + path = proto.Field( + proto.STRING, + number=2, + ) + + mount_path = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + secret = proto.Field( + proto.STRING, + number=3, + ) + versions = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=SecretVersion, + ) + + +class CreateFunctionRequest(proto.Message): + r"""Request for the ``CreateFunction`` method. + + Attributes: + location (str): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + function (google.cloud.functions_v1.types.CloudFunction): + Required. Function to be created. + """ + + location = proto.Field( + proto.STRING, + number=1, + ) + function = proto.Field( + proto.MESSAGE, + number=2, + message='CloudFunction', + ) + + +class UpdateFunctionRequest(proto.Message): + r"""Request for the ``UpdateFunction`` method. + + Attributes: + function (google.cloud.functions_v1.types.CloudFunction): + Required. New version of the function. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields in ``CloudFunction`` that have + to be updated. + """ + + function = proto.Field( + proto.MESSAGE, + number=1, + message='CloudFunction', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetFunctionRequest(proto.Message): + r"""Request for the ``GetFunction`` method. + + Attributes: + name (str): + Required. The name of the function which + details should be obtained. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFunctionsRequest(proto.Message): + r"""Request for the ``ListFunctions`` method. + + Attributes: + parent (str): + The project and location from which the function should be + listed, specified in the format ``projects/*/locations/*`` + If you want to list functions in all locations, use "-" in + place of a location. When listing functions in all + locations, if one or more location(s) are unreachable, the + response will contain functions from all reachable locations + along with the names of any unreachable locations. + page_size (int): + Maximum number of functions to return per + call. + page_token (str): + The value returned by the last ``ListFunctionsResponse``; + indicates that this is a continuation of a prior + ``ListFunctions`` call, and that the system should return + the next page of data. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListFunctionsResponse(proto.Message): + r"""Response for the ``ListFunctions`` method. + + Attributes: + functions (Sequence[google.cloud.functions_v1.types.CloudFunction]): + The functions that match the request. + next_page_token (str): + If not empty, indicates that there may be more functions + that match the request; this value should be passed in a new + [google.cloud.functions.v1.ListFunctionsRequest][google.cloud.functions.v1.ListFunctionsRequest] + to get more functions. + unreachable (Sequence[str]): + Locations that could not be reached. The + response does not include any functions from + these locations. + """ + + @property + def raw_page(self): + return self + + functions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CloudFunction', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + unreachable = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DeleteFunctionRequest(proto.Message): + r"""Request for the ``DeleteFunction`` method. + + Attributes: + name (str): + Required. The name of the function which + should be deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CallFunctionRequest(proto.Message): + r"""Request for the ``CallFunction`` method. + + Attributes: + name (str): + Required. The name of the function to be + called. + data (str): + Required. Input to be passed to the function. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + data = proto.Field( + proto.STRING, + number=2, + ) + + +class CallFunctionResponse(proto.Message): + r"""Response of ``CallFunction`` method. + + Attributes: + execution_id (str): + Execution id of function invocation. + result (str): + Result populated for successful execution of + synchronous function. Will not be populated if + function does not return a result through + context. + error (str): + Either system or user-function generated + error. Set if execution was not successful. + """ + + execution_id = proto.Field( + proto.STRING, + number=1, + ) + result = proto.Field( + proto.STRING, + number=2, + ) + error = proto.Field( + proto.STRING, + number=3, + ) + + +class GenerateUploadUrlRequest(proto.Message): + r"""Request of ``GenerateSourceUploadUrl`` method. + + Attributes: + parent (str): + The project and location in which the Google Cloud Storage + signed URL should be generated, specified in the format + ``projects/*/locations/*``. + kms_key_name (str): + Resource name of a KMS crypto key (managed by the user) used + to encrypt/decrypt function source code objects in staging + Cloud Storage buckets. When you generate an upload url and + upload your source code, it gets copied to a staging Cloud + Storage bucket in an internal regional project. The source + code is then copied to a versioned directory in the sources + bucket in the consumer project during the function + deployment. + + It must match the pattern + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. + + The Google Cloud Functions service account + (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) + must be granted the role 'Cloud KMS CryptoKey + Encrypter/Decrypter + (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the + Key/KeyRing/Project/Organization (least access preferred). + GCF will delegate access to the Google Storage service + account in the internal project. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + kms_key_name = proto.Field( + proto.STRING, + number=2, + ) + + +class GenerateUploadUrlResponse(proto.Message): + r"""Response of ``GenerateSourceUploadUrl`` method. + + Attributes: + upload_url (str): + The generated Google Cloud Storage signed URL + that should be used for a function source code + upload. The uploaded file should be a zip + archive which contains a function. + """ + + upload_url = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateDownloadUrlRequest(proto.Message): + r"""Request of ``GenerateDownloadUrl`` method. + + Attributes: + name (str): + The name of function for which source code + Google Cloud Storage signed URL should be + generated. + version_id (int): + The optional version of function. If not set, + default, current version is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + version_id = proto.Field( + proto.UINT64, + number=2, + ) + + +class GenerateDownloadUrlResponse(proto.Message): + r"""Response of ``GenerateDownloadUrl`` method. + + Attributes: + download_url (str): + The generated Google Cloud Storage signed URL + that should be used for function source code + download. + """ + + download_url = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py new file mode 100644 index 0000000..ab59796 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py @@ -0,0 +1,108 @@ +# -*- 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 any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.functions.v1', + manifest={ + 'OperationType', + 'OperationMetadataV1', + }, +) + + +class OperationType(proto.Enum): + r"""A type of an operation.""" + OPERATION_UNSPECIFIED = 0 + CREATE_FUNCTION = 1 + UPDATE_FUNCTION = 2 + DELETE_FUNCTION = 3 + + +class OperationMetadataV1(proto.Message): + r"""Metadata describing an [Operation][google.longrunning.Operation] + + Attributes: + target (str): + Target of the operation - for example + ``projects/project-1/locations/region-1/functions/function-1`` + type_ (google.cloud.functions_v1.types.OperationType): + Type of operation. + request (google.protobuf.any_pb2.Any): + The original request that started the + operation. + version_id (int): + Version id of the function created or updated + by an API call. This field is only populated for + Create and Update operations. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update timestamp of the operation. + build_id (str): + The Cloud Build ID of the function created or + updated by an API call. This field is only + populated for Create and Update operations. + source_token (str): + An identifier for Firebase function sources. + Disclaimer: This field is only supported for + Firebase function deployments. + build_name (str): + The Cloud Build Name of the function deployment. This field + is only populated for Create and Update operations. + ``projects//locations//builds/``. + """ + + target = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum='OperationType', + ) + request = proto.Field( + proto.MESSAGE, + number=3, + message=any_pb2.Any, + ) + version_id = proto.Field( + proto.INT64, + number=4, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + build_id = proto.Field( + proto.STRING, + number=6, + ) + source_token = proto.Field( + proto.STRING, + number=7, + ) + build_name = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..38940e8 --- /dev/null +++ b/owl-bot-staging/v1/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', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/functions_v1/', + '--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/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py new file mode 100644 index 0000000..f6b67dc --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] +from google.cloud import functions_v1 + + +async def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = await client.call_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py new file mode 100644 index 0000000..7cddbe7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] +from google.cloud import functions_v1 + + +def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = client.call_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py new file mode 100644 index 0000000..dd6b621 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py @@ -0,0 +1,53 @@ +# -*- 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 CreateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] +from google.cloud import functions_v1 + + +async def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py new file mode 100644 index 0000000..117d443 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py @@ -0,0 +1,53 @@ +# -*- 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 CreateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] +from google.cloud import functions_v1 + + +def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py new file mode 100644 index 0000000..3051534 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] +from google.cloud import functions_v1 + + +async def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py new file mode 100644 index 0000000..2262e7b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] +from google.cloud import functions_v1 + + +def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py new file mode 100644 index 0000000..30f6889 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateDownloadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] +from google.cloud import functions_v1 + + +async def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = await client.generate_download_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py new file mode 100644 index 0000000..fbc886f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateDownloadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] +from google.cloud import functions_v1 + + +def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = client.generate_download_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py new file mode 100644 index 0000000..6b19431 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateUploadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] +from google.cloud import functions_v1 + + +async def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = await client.generate_upload_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py new file mode 100644 index 0000000..6e9590a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateUploadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] +from google.cloud import functions_v1 + + +def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = client.generate_upload_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py new file mode 100644 index 0000000..f89b7da --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] +from google.cloud import functions_v1 + + +async def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py new file mode 100644 index 0000000..761c41d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] +from google.cloud import functions_v1 + + +def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = client.get_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py new file mode 100644 index 0000000..09d1b8a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py new file mode 100644 index 0000000..eafe7b7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py new file mode 100644 index 0000000..9a3cd36 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] +from google.cloud import functions_v1 + + +async def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py new file mode 100644 index 0000000..98b3760 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] +from google.cloud import functions_v1 + + +def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py new file mode 100644 index 0000000..2d1128e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py new file mode 100644 index 0000000..b8b14ab --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py new file mode 100644 index 0000000..936744f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py @@ -0,0 +1,47 @@ +# -*- 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py new file mode 100644 index 0000000..c5766f3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py @@ -0,0 +1,47 @@ +# -*- 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py new file mode 100644 index 0000000..4863198 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py @@ -0,0 +1,52 @@ +# -*- 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 UpdateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] +from google.cloud import functions_v1 + + +async def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py new file mode 100644 index 0000000..11809c3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py @@ -0,0 +1,52 @@ +# -*- 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 UpdateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] +from google.cloud import functions_v1 + + +def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json new file mode 100644 index 0000000..9c991cf --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json @@ -0,0 +1,1753 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.functions.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-functions" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.call_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CallFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CallFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "data", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", + "shortName": "call_function" + }, + "description": "Sample for CallFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.call_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CallFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CallFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "data", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", + "shortName": "call_function" + }, + "description": "Sample for CallFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.create_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CreateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CreateFunctionRequest" + }, + { + "name": "location", + "type": "str" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_function" + }, + "description": "Sample for CreateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.create_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CreateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CreateFunctionRequest" + }, + { + "name": "location", + "type": "str" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_function" + }, + "description": "Sample for CreateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.delete_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "DeleteFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_function" + }, + "description": "Sample for DeleteFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.delete_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "DeleteFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_function" + }, + "description": "Sample for DeleteFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_download_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateDownloadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", + "shortName": "generate_download_url" + }, + "description": "Sample for GenerateDownloadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_download_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateDownloadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", + "shortName": "generate_download_url" + }, + "description": "Sample for GenerateDownloadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_upload_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateUploadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", + "shortName": "generate_upload_url" + }, + "description": "Sample for GenerateUploadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_upload_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateUploadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", + "shortName": "generate_upload_url" + }, + "description": "Sample for GenerateUploadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GetFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CloudFunction", + "shortName": "get_function" + }, + "description": "Sample for GetFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GetFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CloudFunction", + "shortName": "get_function" + }, + "description": "Sample for GetFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.list_functions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "ListFunctions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.ListFunctionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager", + "shortName": "list_functions" + }, + "description": "Sample for ListFunctions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.list_functions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "ListFunctions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.ListFunctionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager", + "shortName": "list_functions" + }, + "description": "Sample for ListFunctions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.set_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 43, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 44, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 43, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 44, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.update_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "UpdateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_function" + }, + "description": "Sample for UpdateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.update_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "UpdateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_function" + }, + "description": "Sample for UpdateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py new file mode 100644 index 0000000..6dc057c --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_functions_v1_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 functionsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'call_function': ('name', 'data', ), + 'create_function': ('location', 'function', ), + 'delete_function': ('name', ), + 'generate_download_url': ('name', 'version_id', ), + 'generate_upload_url': ('parent', 'kms_key_name', ), + 'get_function': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'list_functions': ('parent', 'page_size', 'page_token', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_function': ('function', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=functionsCallTransformer(), +): + """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 functions client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..820b19a --- /dev/null +++ b/owl-bot-staging/v1/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-functions', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-functions", + 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] >= 2.8.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.4, < 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/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/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/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/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/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/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/v1/tests/unit/gapic/functions_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__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/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py new file mode 100644 index 0000000..86b090e --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py @@ -0,0 +1,3681 @@ +# -*- 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 +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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.functions_v1.services.cloud_functions_service import CloudFunctionsServiceAsyncClient +from google.cloud.functions_v1.services.cloud_functions_service import CloudFunctionsServiceClient +from google.cloud.functions_v1.services.cloud_functions_service import pagers +from google.cloud.functions_v1.services.cloud_functions_service import transports +from google.cloud.functions_v1.types import functions +from google.cloud.functions_v1.types import operations +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 CloudFunctionsServiceClient._get_default_mtls_endpoint(None) is None + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CloudFunctionsServiceClient, "grpc"), + (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CloudFunctionsServiceGrpcTransport, "grpc"), + (transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CloudFunctionsServiceClient, "grpc"), + (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + + +def test_cloud_functions_service_client_get_transport_class(): + transport = CloudFunctionsServiceClient.get_transport_class() + available_transports = [ + transports.CloudFunctionsServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CloudFunctionsServiceClient.get_transport_class("grpc") + assert transport == transports.CloudFunctionsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) +@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) +def test_cloud_functions_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CloudFunctionsServiceClient, '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(CloudFunctionsServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + 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, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "true"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "false"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) +@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_functions_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CloudFunctionsServiceClient, CloudFunctionsServiceAsyncClient +]) +@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) +@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) +def test_cloud_functions_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_cloud_functions_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_cloud_functions_service_client_client_options_from_dict(): + with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CloudFunctionsServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_cloud_functions_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudfunctions.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="cloudfunctions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + functions.ListFunctionsRequest, + dict, +]) +def test_list_functions(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_functions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListFunctionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFunctionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_functions_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 = CloudFunctionsServiceClient( + 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_functions), + '__call__') as call: + client.list_functions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + +@pytest.mark.asyncio +async def test_list_functions_async(transport: str = 'grpc_asyncio', request_type=functions.ListFunctionsRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_functions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFunctionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_functions_async_from_dict(): + await test_list_functions_async(request_type=dict) + + +def test_list_functions_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListFunctionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__') as call: + call.return_value = functions.ListFunctionsResponse() + client.list_functions(request) + + # Establish that the 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_functions_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListFunctionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse()) + await client.list_functions(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_functions_pager(transport_name: str = "grpc"): + client = CloudFunctionsServiceClient( + 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_functions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_functions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, functions.CloudFunction) + for i in results) +def test_list_functions_pages(transport_name: str = "grpc"): + client = CloudFunctionsServiceClient( + 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_functions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + pages = list(client.list_functions(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_functions_async_pager(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_functions(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, functions.CloudFunction) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_functions_async_pages(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_functions(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", [ + functions.GetFunctionRequest, + dict, +]) +def test_get_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CloudFunction( + name='name_value', + description='description_value', + status=functions.CloudFunctionStatus.ACTIVE, + entry_point='entry_point_value', + runtime='runtime_value', + available_memory_mb=1991, + service_account_email='service_account_email_value', + version_id=1074, + network='network_value', + max_instances=1389, + min_instances=1387, + vpc_connector='vpc_connector_value', + vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, + ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, + kms_key_name='kms_key_name_value', + build_worker_pool='build_worker_pool_value', + build_id='build_id_value', + build_name='build_name_value', + source_token='source_token_value', + docker_repository='docker_repository_value', + docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, + source_archive_url='source_archive_url_value', + https_trigger=functions.HttpsTrigger(url='url_value'), + ) + response = client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CloudFunction) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.status == functions.CloudFunctionStatus.ACTIVE + assert response.entry_point == 'entry_point_value' + assert response.runtime == 'runtime_value' + assert response.available_memory_mb == 1991 + assert response.service_account_email == 'service_account_email_value' + assert response.version_id == 1074 + assert response.network == 'network_value' + assert response.max_instances == 1389 + assert response.min_instances == 1387 + assert response.vpc_connector == 'vpc_connector_value' + assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY + assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL + assert response.kms_key_name == 'kms_key_name_value' + assert response.build_worker_pool == 'build_worker_pool_value' + assert response.build_id == 'build_id_value' + assert response.build_name == 'build_name_value' + assert response.source_token == 'source_token_value' + assert response.docker_repository == 'docker_repository_value' + assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY + + +def test_get_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.get_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + +@pytest.mark.asyncio +async def test_get_function_async(transport: str = 'grpc_asyncio', request_type=functions.GetFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction( + name='name_value', + description='description_value', + status=functions.CloudFunctionStatus.ACTIVE, + entry_point='entry_point_value', + runtime='runtime_value', + available_memory_mb=1991, + service_account_email='service_account_email_value', + version_id=1074, + network='network_value', + max_instances=1389, + min_instances=1387, + vpc_connector='vpc_connector_value', + vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, + ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, + kms_key_name='kms_key_name_value', + build_worker_pool='build_worker_pool_value', + build_id='build_id_value', + build_name='build_name_value', + source_token='source_token_value', + docker_repository='docker_repository_value', + docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, + )) + response = await client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CloudFunction) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.status == functions.CloudFunctionStatus.ACTIVE + assert response.entry_point == 'entry_point_value' + assert response.runtime == 'runtime_value' + assert response.available_memory_mb == 1991 + assert response.service_account_email == 'service_account_email_value' + assert response.version_id == 1074 + assert response.network == 'network_value' + assert response.max_instances == 1389 + assert response.min_instances == 1387 + assert response.vpc_connector == 'vpc_connector_value' + assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY + assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL + assert response.kms_key_name == 'kms_key_name_value' + assert response.build_worker_pool == 'build_worker_pool_value' + assert response.build_id == 'build_id_value' + assert response.build_name == 'build_name_value' + assert response.source_token == 'source_token_value' + assert response.docker_repository == 'docker_repository_value' + assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY + + +@pytest.mark.asyncio +async def test_get_function_async_from_dict(): + await test_get_function_async(request_type=dict) + + +def test_get_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GetFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + call.return_value = functions.CloudFunction() + client.get_function(request) + + # Establish that the 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_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GetFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) + await client.get_function(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_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CloudFunction() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_function( + 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_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.GetFunctionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CloudFunction() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_function( + 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_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.GetFunctionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.CreateFunctionRequest, + dict, +]) +def test_create_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.create_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + +@pytest.mark.asyncio +async def test_create_function_async(transport: str = 'grpc_asyncio', request_type=functions.CreateFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_function_async_from_dict(): + await test_create_function_async(request_type=dict) + + +def test_create_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CreateFunctionRequest() + + request.location = 'location_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_function(request) + + # Establish that the 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', + 'location=location_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CreateFunctionRequest() + + request.location = 'location_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_function(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', + 'location=location_value', + ) in kw['metadata'] + + +def test_create_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__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_function( + location='location_value', + function=functions.CloudFunction(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].location + mock_val = 'location_value' + assert arg == mock_val + arg = args[0].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + + +def test_create_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.CreateFunctionRequest(), + location='location_value', + function=functions.CloudFunction(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__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_function( + location='location_value', + function=functions.CloudFunction(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].location + mock_val = 'location_value' + assert arg == mock_val + arg = args[0].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.CreateFunctionRequest(), + location='location_value', + function=functions.CloudFunction(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + functions.UpdateFunctionRequest, + dict, +]) +def test_update_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.update_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + +@pytest.mark.asyncio +async def test_update_function_async(transport: str = 'grpc_asyncio', request_type=functions.UpdateFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_function_async_from_dict(): + await test_update_function_async(request_type=dict) + + +def test_update_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.UpdateFunctionRequest() + + request.function.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_function(request) + + # Establish that the 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', + 'function.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.UpdateFunctionRequest() + + request.function.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_function(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', + 'function.name=name_value', + ) in kw['metadata'] + + +def test_update_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__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_function( + function=functions.CloudFunction(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].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + + +def test_update_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.UpdateFunctionRequest(), + function=functions.CloudFunction(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__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_function( + function=functions.CloudFunction(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].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.UpdateFunctionRequest(), + function=functions.CloudFunction(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + functions.DeleteFunctionRequest, + dict, +]) +def test_delete_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.delete_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + +@pytest.mark.asyncio +async def test_delete_function_async(transport: str = 'grpc_asyncio', request_type=functions.DeleteFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_function_async_from_dict(): + await test_delete_function_async(request_type=dict) + + +def test_delete_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.DeleteFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_function(request) + + # Establish that the 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_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.DeleteFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_function(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_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__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_function( + 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_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.DeleteFunctionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__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_function( + 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_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.DeleteFunctionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.CallFunctionRequest, + dict, +]) +def test_call_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CallFunctionResponse( + execution_id='execution_id_value', + result='result_value', + error='error_value', + ) + response = client.call_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CallFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CallFunctionResponse) + assert response.execution_id == 'execution_id_value' + assert response.result == 'result_value' + assert response.error == 'error_value' + + +def test_call_function_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 = CloudFunctionsServiceClient( + 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.call_function), + '__call__') as call: + client.call_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CallFunctionRequest() + +@pytest.mark.asyncio +async def test_call_function_async(transport: str = 'grpc_asyncio', request_type=functions.CallFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse( + execution_id='execution_id_value', + result='result_value', + error='error_value', + )) + response = await client.call_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CallFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CallFunctionResponse) + assert response.execution_id == 'execution_id_value' + assert response.result == 'result_value' + assert response.error == 'error_value' + + +@pytest.mark.asyncio +async def test_call_function_async_from_dict(): + await test_call_function_async(request_type=dict) + + +def test_call_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CallFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + call.return_value = functions.CallFunctionResponse() + client.call_function(request) + + # Establish that the 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_call_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CallFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) + await client.call_function(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_call_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CallFunctionResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.call_function( + name='name_value', + data='data_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 + arg = args[0].data + mock_val = 'data_value' + assert arg == mock_val + + +def test_call_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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.call_function( + functions.CallFunctionRequest(), + name='name_value', + data='data_value', + ) + +@pytest.mark.asyncio +async def test_call_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CallFunctionResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.call_function( + name='name_value', + data='data_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 + arg = args[0].data + mock_val = 'data_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_call_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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.call_function( + functions.CallFunctionRequest(), + name='name_value', + data='data_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.GenerateUploadUrlRequest, + dict, +]) +def test_generate_upload_url(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.GenerateUploadUrlResponse( + upload_url='upload_url_value', + ) + response = client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateUploadUrlResponse) + assert response.upload_url == 'upload_url_value' + + +def test_generate_upload_url_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 = CloudFunctionsServiceClient( + 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.generate_upload_url), + '__call__') as call: + client.generate_upload_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + +@pytest.mark.asyncio +async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateUploadUrlRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse( + upload_url='upload_url_value', + )) + response = await client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateUploadUrlResponse) + assert response.upload_url == 'upload_url_value' + + +@pytest.mark.asyncio +async def test_generate_upload_url_async_from_dict(): + await test_generate_upload_url_async(request_type=dict) + + +def test_generate_upload_url_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateUploadUrlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + call.return_value = functions.GenerateUploadUrlResponse() + client.generate_upload_url(request) + + # Establish that the 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_generate_upload_url_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateUploadUrlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse()) + await client.generate_upload_url(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'] + + +@pytest.mark.parametrize("request_type", [ + functions.GenerateDownloadUrlRequest, + dict, +]) +def test_generate_download_url(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.GenerateDownloadUrlResponse( + download_url='download_url_value', + ) + response = client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateDownloadUrlResponse) + assert response.download_url == 'download_url_value' + + +def test_generate_download_url_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 = CloudFunctionsServiceClient( + 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.generate_download_url), + '__call__') as call: + client.generate_download_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + +@pytest.mark.asyncio +async def test_generate_download_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateDownloadUrlRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse( + download_url='download_url_value', + )) + response = await client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateDownloadUrlResponse) + assert response.download_url == 'download_url_value' + + +@pytest.mark.asyncio +async def test_generate_download_url_async_from_dict(): + await test_generate_download_url_async(request_type=dict) + + +def test_generate_download_url_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateDownloadUrlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + call.return_value = functions.GenerateDownloadUrlResponse() + client.generate_download_url(request) + + # Establish that the 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_generate_download_url_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateDownloadUrlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse()) + await client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceClient( + 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.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceClient( + 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.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceClient( + 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.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudFunctionsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, +]) +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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudFunctionsServiceGrpcTransport, + ) + +def test_cloud_functions_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudFunctionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_cloud_functions_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CloudFunctionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_functions', + 'get_function', + 'create_function', + 'update_function', + 'delete_function', + 'call_function', + 'generate_upload_url', + 'generate_download_url', + 'set_iam_policy', + 'get_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_cloud_functions_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudFunctionsServiceTransport( + 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_cloud_functions_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudFunctionsServiceTransport() + adc.assert_called_once() + + +def test_cloud_functions_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudFunctionsServiceClient() + 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.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_functions_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_functions_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudFunctionsServiceGrpcTransport, grpc_helpers), + (transports.CloudFunctionsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_cloud_functions_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "cloudfunctions.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="cloudfunctions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) +def test_cloud_functions_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_cloud_functions_service_host_no_port(transport_name): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_cloud_functions_service_host_with_port(transport_name): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:8000' + ) + +def test_cloud_functions_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudFunctionsServiceGrpcTransport( + 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_cloud_functions_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( + 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.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) +def test_cloud_functions_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) +def test_cloud_functions_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_cloud_functions_service_grpc_lro_client(): + client = CloudFunctionsServiceClient( + 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_cloud_functions_service_grpc_lro_async_client(): + client = CloudFunctionsServiceAsyncClient( + 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_cloud_function_path(): + project = "squid" + location = "clam" + function = "whelk" + expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + actual = CloudFunctionsServiceClient.cloud_function_path(project, location, function) + assert expected == actual + + +def test_parse_cloud_function_path(): + expected = { + "project": "octopus", + "location": "oyster", + "function": "nudibranch", + } + path = CloudFunctionsServiceClient.cloud_function_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_cloud_function_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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_crypto_key_path(path) + assert expected == actual + +def test_repository_path(): + project = "whelk" + location = "octopus" + repository = "oyster" + expected = "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) + actual = CloudFunctionsServiceClient.repository_path(project, location, repository) + assert expected == actual + + +def test_parse_repository_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "repository": "mussel", + } + path = CloudFunctionsServiceClient.repository_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_repository_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CloudFunctionsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = CloudFunctionsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = CloudFunctionsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = CloudFunctionsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CloudFunctionsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = CloudFunctionsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = CloudFunctionsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = CloudFunctionsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CloudFunctionsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = CloudFunctionsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.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.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CloudFunctionsServiceClient.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 = CloudFunctionsServiceAsyncClient( + 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceClient( + 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", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport), +]) +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, + api_audience=None, + ) From 894032d81f530df20bcb22eb8ef4bf9d17c115ef Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 5 Jul 2022 23:40:03 +0000 Subject: [PATCH 04/16] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-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 --- owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/.flake8 | 33 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 -- .../functions_v1/cloud_functions_service.rst | 10 - .../v1/docs/functions_v1/services.rst | 6 - .../v1/docs/functions_v1/types.rst | 7 - owl-bot-staging/v1/docs/index.rst | 7 - .../v1/google/cloud/functions/__init__.py | 67 - .../v1/google/cloud/functions/py.typed | 2 - .../v1/google/cloud/functions_v1/__init__.py | 68 - .../cloud/functions_v1/gapic_metadata.json | 133 - .../v1/google/cloud/functions_v1/py.typed | 2 - .../cloud/functions_v1/services/__init__.py | 15 - .../cloud_functions_service/__init__.py | 22 - .../cloud_functions_service/async_client.py | 1423 ------- .../cloud_functions_service/client.py | 1613 -------- .../cloud_functions_service/pagers.py | 139 - .../transports/__init__.py | 33 - .../transports/base.py | 331 -- .../transports/grpc.py | 593 --- .../transports/grpc_asyncio.py | 592 --- .../cloud/functions_v1/types/__init__.py | 66 - .../cloud/functions_v1/types/functions.py | 1067 ----- .../cloud/functions_v1/types/operations.py | 108 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 180 - ...d_functions_service_call_function_async.py | 46 - ...ud_functions_service_call_function_sync.py | 46 - ...functions_service_create_function_async.py | 53 - ..._functions_service_create_function_sync.py | 53 - ...functions_service_delete_function_async.py | 49 - ..._functions_service_delete_function_sync.py | 49 - ...ons_service_generate_download_url_async.py | 44 - ...ions_service_generate_download_url_sync.py | 44 - ...tions_service_generate_upload_url_async.py | 44 - ...ctions_service_generate_upload_url_sync.py | 44 - ...ud_functions_service_get_function_async.py | 45 - ...oud_functions_service_get_function_sync.py | 45 - ..._functions_service_get_iam_policy_async.py | 46 - ...d_functions_service_get_iam_policy_sync.py | 46 - ..._functions_service_list_functions_async.py | 45 - ...d_functions_service_list_functions_sync.py | 45 - ..._functions_service_set_iam_policy_async.py | 46 - ...d_functions_service_set_iam_policy_sync.py | 46 - ...ions_service_test_iam_permissions_async.py | 47 - ...tions_service_test_iam_permissions_sync.py | 47 - ...functions_service_update_function_async.py | 52 - ..._functions_service_update_function_sync.py | 52 - .../snippet_metadata_functions_v1.json | 1753 -------- .../v1/scripts/fixup_functions_v1_keywords.py | 186 - owl-bot-staging/v1/setup.py | 60 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/functions_v1/__init__.py | 16 - .../test_cloud_functions_service.py | 3681 ----------------- .../test_cloud_functions_service.py | 1 - 59 files changed, 13743 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/.flake8 delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst delete mode 100644 owl-bot-staging/v1/docs/functions_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/functions_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/google/cloud/functions/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json delete mode 100644 owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index ca93bdf..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/functions/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 deleted file mode 100644 index 29227d4..0000000 --- a/owl-bot-staging/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 9e8399a..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/functions *.py -recursive-include google/cloud/functions_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 533650a..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Functions 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 Functions API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 3464a12..0000000 --- a/owl-bot-staging/v1/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-functions 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-functions" -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-functions-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-functions.tex", - u"google-cloud-functions 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-functions", - u"Google Cloud Functions 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-functions", - u"google-cloud-functions Documentation", - author, - "google-cloud-functions", - "GAPIC library for Google Cloud Functions API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst b/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst deleted file mode 100644 index 36d0114..0000000 --- a/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CloudFunctionsService ---------------------------------------- - -.. automodule:: google.cloud.functions_v1.services.cloud_functions_service - :members: - :inherited-members: - -.. automodule:: google.cloud.functions_v1.services.cloud_functions_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/functions_v1/services.rst b/owl-bot-staging/v1/docs/functions_v1/services.rst deleted file mode 100644 index 89ae970..0000000 --- a/owl-bot-staging/v1/docs/functions_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Functions v1 API -========================================== -.. toctree:: - :maxdepth: 2 - - cloud_functions_service diff --git a/owl-bot-staging/v1/docs/functions_v1/types.rst b/owl-bot-staging/v1/docs/functions_v1/types.rst deleted file mode 100644 index bebdfe9..0000000 --- a/owl-bot-staging/v1/docs/functions_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Functions v1 API -======================================= - -.. automodule:: google.cloud.functions_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index dc30f6d..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - functions_v1/services - functions_v1/types diff --git a/owl-bot-staging/v1/google/cloud/functions/__init__.py b/owl-bot-staging/v1/google/cloud/functions/__init__.py deleted file mode 100644 index c34f3b0..0000000 --- a/owl-bot-staging/v1/google/cloud/functions/__init__.py +++ /dev/null @@ -1,67 +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.functions_v1.services.cloud_functions_service.client import CloudFunctionsServiceClient -from google.cloud.functions_v1.services.cloud_functions_service.async_client import CloudFunctionsServiceAsyncClient - -from google.cloud.functions_v1.types.functions import CallFunctionRequest -from google.cloud.functions_v1.types.functions import CallFunctionResponse -from google.cloud.functions_v1.types.functions import CloudFunction -from google.cloud.functions_v1.types.functions import CreateFunctionRequest -from google.cloud.functions_v1.types.functions import DeleteFunctionRequest -from google.cloud.functions_v1.types.functions import EventTrigger -from google.cloud.functions_v1.types.functions import FailurePolicy -from google.cloud.functions_v1.types.functions import GenerateDownloadUrlRequest -from google.cloud.functions_v1.types.functions import GenerateDownloadUrlResponse -from google.cloud.functions_v1.types.functions import GenerateUploadUrlRequest -from google.cloud.functions_v1.types.functions import GenerateUploadUrlResponse -from google.cloud.functions_v1.types.functions import GetFunctionRequest -from google.cloud.functions_v1.types.functions import HttpsTrigger -from google.cloud.functions_v1.types.functions import ListFunctionsRequest -from google.cloud.functions_v1.types.functions import ListFunctionsResponse -from google.cloud.functions_v1.types.functions import SecretEnvVar -from google.cloud.functions_v1.types.functions import SecretVolume -from google.cloud.functions_v1.types.functions import SourceRepository -from google.cloud.functions_v1.types.functions import UpdateFunctionRequest -from google.cloud.functions_v1.types.functions import CloudFunctionStatus -from google.cloud.functions_v1.types.operations import OperationMetadataV1 -from google.cloud.functions_v1.types.operations import OperationType - -__all__ = ('CloudFunctionsServiceClient', - 'CloudFunctionsServiceAsyncClient', - 'CallFunctionRequest', - 'CallFunctionResponse', - 'CloudFunction', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventTrigger', - 'FailurePolicy', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'HttpsTrigger', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'SecretEnvVar', - 'SecretVolume', - 'SourceRepository', - 'UpdateFunctionRequest', - 'CloudFunctionStatus', - 'OperationMetadataV1', - 'OperationType', -) diff --git a/owl-bot-staging/v1/google/cloud/functions/py.typed b/owl-bot-staging/v1/google/cloud/functions/py.typed deleted file mode 100644 index 982ebb1..0000000 --- a/owl-bot-staging/v1/google/cloud/functions/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py deleted file mode 100644 index 87351c6..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py +++ /dev/null @@ -1,68 +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.cloud_functions_service import CloudFunctionsServiceClient -from .services.cloud_functions_service import CloudFunctionsServiceAsyncClient - -from .types.functions import CallFunctionRequest -from .types.functions import CallFunctionResponse -from .types.functions import CloudFunction -from .types.functions import CreateFunctionRequest -from .types.functions import DeleteFunctionRequest -from .types.functions import EventTrigger -from .types.functions import FailurePolicy -from .types.functions import GenerateDownloadUrlRequest -from .types.functions import GenerateDownloadUrlResponse -from .types.functions import GenerateUploadUrlRequest -from .types.functions import GenerateUploadUrlResponse -from .types.functions import GetFunctionRequest -from .types.functions import HttpsTrigger -from .types.functions import ListFunctionsRequest -from .types.functions import ListFunctionsResponse -from .types.functions import SecretEnvVar -from .types.functions import SecretVolume -from .types.functions import SourceRepository -from .types.functions import UpdateFunctionRequest -from .types.functions import CloudFunctionStatus -from .types.operations import OperationMetadataV1 -from .types.operations import OperationType - -__all__ = ( - 'CloudFunctionsServiceAsyncClient', -'CallFunctionRequest', -'CallFunctionResponse', -'CloudFunction', -'CloudFunctionStatus', -'CloudFunctionsServiceClient', -'CreateFunctionRequest', -'DeleteFunctionRequest', -'EventTrigger', -'FailurePolicy', -'GenerateDownloadUrlRequest', -'GenerateDownloadUrlResponse', -'GenerateUploadUrlRequest', -'GenerateUploadUrlResponse', -'GetFunctionRequest', -'HttpsTrigger', -'ListFunctionsRequest', -'ListFunctionsResponse', -'OperationMetadataV1', -'OperationType', -'SecretEnvVar', -'SecretVolume', -'SourceRepository', -'UpdateFunctionRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json deleted file mode 100644 index 5745d05..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json +++ /dev/null @@ -1,133 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.functions_v1", - "protoPackage": "google.cloud.functions.v1", - "schema": "1.0", - "services": { - "CloudFunctionsService": { - "clients": { - "grpc": { - "libraryClient": "CloudFunctionsServiceClient", - "rpcs": { - "CallFunction": { - "methods": [ - "call_function" - ] - }, - "CreateFunction": { - "methods": [ - "create_function" - ] - }, - "DeleteFunction": { - "methods": [ - "delete_function" - ] - }, - "GenerateDownloadUrl": { - "methods": [ - "generate_download_url" - ] - }, - "GenerateUploadUrl": { - "methods": [ - "generate_upload_url" - ] - }, - "GetFunction": { - "methods": [ - "get_function" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFunctions": { - "methods": [ - "list_functions" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFunction": { - "methods": [ - "update_function" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CloudFunctionsServiceAsyncClient", - "rpcs": { - "CallFunction": { - "methods": [ - "call_function" - ] - }, - "CreateFunction": { - "methods": [ - "create_function" - ] - }, - "DeleteFunction": { - "methods": [ - "delete_function" - ] - }, - "GenerateDownloadUrl": { - "methods": [ - "generate_download_url" - ] - }, - "GenerateUploadUrl": { - "methods": [ - "generate_upload_url" - ] - }, - "GetFunction": { - "methods": [ - "get_function" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFunctions": { - "methods": [ - "list_functions" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFunction": { - "methods": [ - "update_function" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/py.typed b/owl-bot-staging/v1/google/cloud/functions_v1/py.typed deleted file mode 100644 index 982ebb1..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py deleted file mode 100644 index e8e1c38..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/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/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py deleted file mode 100644 index d784dc7..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__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 CloudFunctionsServiceClient -from .async_client import CloudFunctionsServiceAsyncClient - -__all__ = ( - 'CloudFunctionsServiceClient', - 'CloudFunctionsServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py deleted file mode 100644 index 3010041..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py +++ /dev/null @@ -1,1423 +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_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport -from .client import CloudFunctionsServiceClient - - -class CloudFunctionsServiceAsyncClient: - """A service that application uses to manipulate triggers and - functions. - """ - - _client: CloudFunctionsServiceClient - - DEFAULT_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT - - cloud_function_path = staticmethod(CloudFunctionsServiceClient.cloud_function_path) - parse_cloud_function_path = staticmethod(CloudFunctionsServiceClient.parse_cloud_function_path) - crypto_key_path = staticmethod(CloudFunctionsServiceClient.crypto_key_path) - parse_crypto_key_path = staticmethod(CloudFunctionsServiceClient.parse_crypto_key_path) - repository_path = staticmethod(CloudFunctionsServiceClient.repository_path) - parse_repository_path = staticmethod(CloudFunctionsServiceClient.parse_repository_path) - common_billing_account_path = staticmethod(CloudFunctionsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CloudFunctionsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CloudFunctionsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CloudFunctionsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CloudFunctionsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CloudFunctionsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CloudFunctionsServiceClient.common_project_path) - parse_common_project_path = staticmethod(CloudFunctionsServiceClient.parse_common_project_path) - common_location_path = staticmethod(CloudFunctionsServiceClient.common_location_path) - parse_common_location_path = staticmethod(CloudFunctionsServiceClient.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: - CloudFunctionsServiceAsyncClient: The constructed client. - """ - return CloudFunctionsServiceClient.from_service_account_info.__func__(CloudFunctionsServiceAsyncClient, 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: - CloudFunctionsServiceAsyncClient: The constructed client. - """ - return CloudFunctionsServiceClient.from_service_account_file.__func__(CloudFunctionsServiceAsyncClient, 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 CloudFunctionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CloudFunctionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CloudFunctionsServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CloudFunctionsServiceClient).get_transport_class, type(CloudFunctionsServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CloudFunctionsServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the cloud functions service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CloudFunctionsServiceTransport]): 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 = CloudFunctionsServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_functions(self, - request: Union[functions.ListFunctionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsAsyncPager: - r"""Returns a list of functions that belong to the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): - The request object. Request for the `ListFunctions` - 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager: - Response for the ListFunctions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = functions.ListFunctionsRequest(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.list_functions, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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.ListFunctionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_function(self, - request: Union[functions.GetFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CloudFunction: - r"""Returns a function with the given name from the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): - The request object. Request for the `GetFunction` - method. - name (:class:`str`): - Required. The name of the function - which details should be obtained. - - 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.functions_v1.types.CloudFunction: - Describes a Cloud Function that - contains user computation executed in - response to an event. It encapsulate - function and triggers configurations. - - """ - # 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 = functions.GetFunctionRequest(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_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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 create_function(self, - request: Union[functions.CreateFunctionRequest, dict] = None, - *, - location: str = None, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): - The request object. Request for the `CreateFunction` - method. - location (:class:`str`): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - function (:class:`google.cloud.functions_v1.types.CloudFunction`): - Required. Function to be created. - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([location, function]) - if request is 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 = functions.CreateFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if function is not None: - request.function = function - - # 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_function, - default_timeout=600.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(( - ("location", request.location), - )), - ) - - # 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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def update_function(self, - request: Union[functions.UpdateFunctionRequest, dict] = None, - *, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates existing function. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): - The request object. Request for the `UpdateFunction` - method. - function (:class:`google.cloud.functions_v1.types.CloudFunction`): - Required. New version of the - function. - - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([function]) - if request is 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 = functions.UpdateFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if function is not None: - request.function = function - - # 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_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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(( - ("function.name", request.function.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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def delete_function(self, - request: Union[functions.DeleteFunctionRequest, 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 function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): - The request object. Request for the `DeleteFunction` - method. - name (:class:`str`): - Required. The name of the function - which should be deleted. - - 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.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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 = functions.DeleteFunctionRequest(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_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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, - empty_pb2.Empty, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def call_function(self, - request: Union[functions.CallFunctionRequest, dict] = None, - *, - name: str = None, - data: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CallFunctionResponse: - r"""Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = await client.call_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): - The request object. Request for the `CallFunction` - method. - name (:class:`str`): - Required. The name of the function to - be called. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (:class:`str`): - Required. Input to be passed to the - function. - - This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: - Response of CallFunction method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, data]) - if request is 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 = functions.CallFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.call_function, - default_timeout=600.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 generate_upload_url(self, - request: Union[functions.GenerateUploadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateUploadUrlResponse: - r"""Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = await client.generate_upload_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): - The request object. Request of `GenerateSourceUploadUrl` - 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.cloud.functions_v1.types.GenerateUploadUrlResponse: - Response of GenerateSourceUploadUrl method. - """ - # Create or coerce a protobuf request object. - request = functions.GenerateUploadUrlRequest(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.generate_upload_url, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def generate_download_url(self, - request: Union[functions.GenerateDownloadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateDownloadUrlResponse: - r"""Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = await client.generate_download_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): - The request object. Request of `GenerateDownloadUrl` - 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: - Response of GenerateDownloadUrl method. - """ - # Create or coerce a protobuf request object. - request = functions.GenerateDownloadUrlRequest(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.generate_download_url, - 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 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 on the specified - function. Replaces any existing policy. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await 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 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"""Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await 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 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"""Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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) - - 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-functions", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CloudFunctionsServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py deleted file mode 100644 index 53c6f1a..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py +++ /dev/null @@ -1,1613 +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_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CloudFunctionsServiceGrpcTransport -from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport - - -class CloudFunctionsServiceClientMeta(type): - """Metaclass for the CloudFunctionsService 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[CloudFunctionsServiceTransport]] - _transport_registry["grpc"] = CloudFunctionsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CloudFunctionsServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CloudFunctionsServiceTransport]: - """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 CloudFunctionsServiceClient(metaclass=CloudFunctionsServiceClientMeta): - """A service that application uses to manipulate triggers and - functions. - """ - - @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 = "cloudfunctions.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: - CloudFunctionsServiceClient: 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: - CloudFunctionsServiceClient: 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) -> CloudFunctionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CloudFunctionsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def cloud_function_path(project: str,location: str,function: str,) -> str: - """Returns a fully-qualified cloud_function string.""" - return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) - - @staticmethod - def parse_cloud_function_path(path: str) -> Dict[str,str]: - """Parses a cloud_function path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?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 repository_path(project: str,location: str,repository: str,) -> str: - """Returns a fully-qualified repository string.""" - return "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) - - @staticmethod - def parse_repository_path(path: str) -> Dict[str,str]: - """Parses a repository path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/repositories/(?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, CloudFunctionsServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the cloud functions service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CloudFunctionsServiceTransport]): 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, CloudFunctionsServiceTransport): - # transport is a CloudFunctionsServiceTransport 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, - api_audience=client_options.api_audience, - ) - - def list_functions(self, - request: Union[functions.ListFunctionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsPager: - r"""Returns a list of functions that belong to the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): - The request object. Request for the `ListFunctions` - 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager: - Response for the ListFunctions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a functions.ListFunctionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.ListFunctionsRequest): - request = functions.ListFunctionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_functions] - - # 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.ListFunctionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_function(self, - request: Union[functions.GetFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CloudFunction: - r"""Returns a function with the given name from the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = client.get_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): - The request object. Request for the `GetFunction` - method. - name (str): - Required. The name of the function - which details should be obtained. - - 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.functions_v1.types.CloudFunction: - Describes a Cloud Function that - contains user computation executed in - response to an event. It encapsulate - function and triggers configurations. - - """ - # 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 functions.GetFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.GetFunctionRequest): - request = functions.GetFunctionRequest(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_function] - - # 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 create_function(self, - request: Union[functions.CreateFunctionRequest, dict] = None, - *, - location: str = None, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): - The request object. Request for the `CreateFunction` - method. - location (str): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - function (google.cloud.functions_v1.types.CloudFunction): - Required. Function to be created. - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([location, function]) - if request is 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 functions.CreateFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.CreateFunctionRequest): - request = functions.CreateFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if function is not None: - request.function = function - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_function] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("location", request.location), - )), - ) - - # 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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def update_function(self, - request: Union[functions.UpdateFunctionRequest, dict] = None, - *, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates existing function. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): - The request object. Request for the `UpdateFunction` - method. - function (google.cloud.functions_v1.types.CloudFunction): - Required. New version of the - function. - - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([function]) - if request is 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 functions.UpdateFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.UpdateFunctionRequest): - request = functions.UpdateFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if function is not None: - request.function = function - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_function] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("function.name", request.function.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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def delete_function(self, - request: Union[functions.DeleteFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): - The request object. Request for the `DeleteFunction` - method. - name (str): - Required. The name of the function - which should be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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 functions.DeleteFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.DeleteFunctionRequest): - request = functions.DeleteFunctionRequest(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_function] - - # 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, - empty_pb2.Empty, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def call_function(self, - request: Union[functions.CallFunctionRequest, dict] = None, - *, - name: str = None, - data: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CallFunctionResponse: - r"""Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = client.call_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): - The request object. Request for the `CallFunction` - method. - name (str): - Required. The name of the function to - be called. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (str): - Required. Input to be passed to the - function. - - This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: - Response of CallFunction method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, data]) - if request is 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 functions.CallFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.CallFunctionRequest): - request = functions.CallFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.call_function] - - # 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 generate_upload_url(self, - request: Union[functions.GenerateUploadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateUploadUrlResponse: - r"""Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = client.generate_upload_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): - The request object. Request of `GenerateSourceUploadUrl` - 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.cloud.functions_v1.types.GenerateUploadUrlResponse: - Response of GenerateSourceUploadUrl method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a functions.GenerateUploadUrlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.GenerateUploadUrlRequest): - request = functions.GenerateUploadUrlRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_upload_url] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_download_url(self, - request: Union[functions.GenerateDownloadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateDownloadUrlResponse: - r"""Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = client.generate_download_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): - The request object. Request of `GenerateDownloadUrl` - 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: - Response of GenerateDownloadUrl method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a functions.GenerateDownloadUrlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.GenerateDownloadUrlRequest): - request = functions.GenerateDownloadUrlRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_download_url] - - # 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 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 on the specified - function. Replaces any existing policy. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 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"""Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 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"""Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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-functions", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CloudFunctionsServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py deleted file mode 100644 index f31d4f1..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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.functions_v1.types import functions - - -class ListFunctionsPager: - """A pager for iterating through ``list_functions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``functions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFunctions`` requests and continue to iterate - through the ``functions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` - 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[..., functions.ListFunctionsResponse], - request: functions.ListFunctionsRequest, - response: functions.ListFunctionsResponse, - *, - 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.functions_v1.types.ListFunctionsRequest): - The initial request object. - response (google.cloud.functions_v1.types.ListFunctionsResponse): - 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 = functions.ListFunctionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[functions.ListFunctionsResponse]: - 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[functions.CloudFunction]: - for page in self.pages: - yield from page.functions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFunctionsAsyncPager: - """A pager for iterating through ``list_functions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``functions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFunctions`` requests and continue to iterate - through the ``functions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` - 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[functions.ListFunctionsResponse]], - request: functions.ListFunctionsRequest, - response: functions.ListFunctionsResponse, - *, - 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.functions_v1.types.ListFunctionsRequest): - The initial request object. - response (google.cloud.functions_v1.types.ListFunctionsResponse): - 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 = functions.ListFunctionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[functions.ListFunctionsResponse]: - 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[functions.CloudFunction]: - async def async_generator(): - async for page in self.pages: - for response in page.functions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py deleted file mode 100644 index ac1ba7e..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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 CloudFunctionsServiceTransport -from .grpc import CloudFunctionsServiceGrpcTransport -from .grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CloudFunctionsServiceTransport]] -_transport_registry['grpc'] = CloudFunctionsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CloudFunctionsServiceGrpcAsyncIOTransport - -__all__ = ( - 'CloudFunctionsServiceTransport', - 'CloudFunctionsServiceGrpcTransport', - 'CloudFunctionsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py deleted file mode 100644 index 2d3352f..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py +++ /dev/null @@ -1,331 +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.functions_v1.types import functions -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-functions', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CloudFunctionsServiceTransport(abc.ABC): - """Abstract transport class for CloudFunctionsService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'cloudfunctions.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, - api_audience: Optional[str] = None, - **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. - """ - - 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) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_functions: gapic_v1.method.wrap_method( - self.list_functions, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_function: gapic_v1.method.wrap_method( - self.get_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.create_function: gapic_v1.method.wrap_method( - self.create_function, - default_timeout=600.0, - client_info=client_info, - ), - self.update_function: gapic_v1.method.wrap_method( - self.update_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.delete_function: gapic_v1.method.wrap_method( - self.delete_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.call_function: gapic_v1.method.wrap_method( - self.call_function, - default_timeout=600.0, - client_info=client_info, - ), - self.generate_upload_url: gapic_v1.method.wrap_method( - self.generate_upload_url, - default_timeout=None, - client_info=client_info, - ), - self.generate_download_url: gapic_v1.method.wrap_method( - self.generate_download_url, - 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.get_iam_policy: gapic_v1.method.wrap_method( - self.get_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 list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - Union[ - functions.ListFunctionsResponse, - Awaitable[functions.ListFunctionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - Union[ - functions.CloudFunction, - Awaitable[functions.CloudFunction] - ]]: - raise NotImplementedError() - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - Union[ - functions.CallFunctionResponse, - Awaitable[functions.CallFunctionResponse] - ]]: - raise NotImplementedError() - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - Union[ - functions.GenerateUploadUrlResponse, - Awaitable[functions.GenerateUploadUrlResponse] - ]]: - raise NotImplementedError() - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - Union[ - functions.GenerateDownloadUrlResponse, - Awaitable[functions.GenerateDownloadUrlResponse] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CloudFunctionsServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py deleted file mode 100644 index 92c02c9..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py +++ /dev/null @@ -1,593 +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.functions_v1.types import functions -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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO - - -class CloudFunctionsServiceGrpcTransport(CloudFunctionsServiceTransport): - """gRPC backend transport for CloudFunctionsService. - - A service that application uses to manipulate triggers and - functions. - - 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 = 'cloudfunctions.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, - api_audience: Optional[str] = None, - ) -> 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, - api_audience=api_audience, - ) - - 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 = 'cloudfunctions.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 list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - functions.ListFunctionsResponse]: - r"""Return a callable for the list functions method over gRPC. - - Returns a list of functions that belong to the - requested project. - - Returns: - Callable[[~.ListFunctionsRequest], - ~.ListFunctionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_functions' not in self._stubs: - self._stubs['list_functions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', - request_serializer=functions.ListFunctionsRequest.serialize, - response_deserializer=functions.ListFunctionsResponse.deserialize, - ) - return self._stubs['list_functions'] - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - functions.CloudFunction]: - r"""Return a callable for the get function method over gRPC. - - Returns a function with the given name from the - requested project. - - Returns: - Callable[[~.GetFunctionRequest], - ~.CloudFunction]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_function' not in self._stubs: - self._stubs['get_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', - request_serializer=functions.GetFunctionRequest.serialize, - response_deserializer=functions.CloudFunction.deserialize, - ) - return self._stubs['get_function'] - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create function method over gRPC. - - Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - Returns: - Callable[[~.CreateFunctionRequest], - ~.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_function' not in self._stubs: - self._stubs['create_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', - request_serializer=functions.CreateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_function'] - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - operations_pb2.Operation]: - r"""Return a callable for the update function method over gRPC. - - Updates existing function. - - Returns: - Callable[[~.UpdateFunctionRequest], - ~.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_function' not in self._stubs: - self._stubs['update_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', - request_serializer=functions.UpdateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_function'] - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete function method over gRPC. - - Deletes a function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - Returns: - Callable[[~.DeleteFunctionRequest], - ~.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_function' not in self._stubs: - self._stubs['delete_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', - request_serializer=functions.DeleteFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_function'] - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - functions.CallFunctionResponse]: - r"""Return a callable for the call function method over gRPC. - - Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - Returns: - Callable[[~.CallFunctionRequest], - ~.CallFunctionResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'call_function' not in self._stubs: - self._stubs['call_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', - request_serializer=functions.CallFunctionRequest.serialize, - response_deserializer=functions.CallFunctionResponse.deserialize, - ) - return self._stubs['call_function'] - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - functions.GenerateUploadUrlResponse]: - r"""Return a callable for the generate upload url method over gRPC. - - Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - Returns: - Callable[[~.GenerateUploadUrlRequest], - ~.GenerateUploadUrlResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_upload_url' not in self._stubs: - self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', - request_serializer=functions.GenerateUploadUrlRequest.serialize, - response_deserializer=functions.GenerateUploadUrlResponse.deserialize, - ) - return self._stubs['generate_upload_url'] - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - functions.GenerateDownloadUrlResponse]: - r"""Return a callable for the generate download url method over gRPC. - - Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - Returns: - Callable[[~.GenerateDownloadUrlRequest], - ~.GenerateDownloadUrlResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_download_url' not in self._stubs: - self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', - request_serializer=functions.GenerateDownloadUrlRequest.serialize, - response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, - ) - return self._stubs['generate_download_url'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - r"""Return a callable for the test iam permissions method over gRPC. - - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/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__ = ( - 'CloudFunctionsServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py deleted file mode 100644 index d05047d..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,592 +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.functions_v1.types import functions -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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CloudFunctionsServiceGrpcTransport - - -class CloudFunctionsServiceGrpcAsyncIOTransport(CloudFunctionsServiceTransport): - """gRPC AsyncIO backend transport for CloudFunctionsService. - - A service that application uses to manipulate triggers and - functions. - - 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 = 'cloudfunctions.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 = 'cloudfunctions.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, - api_audience: Optional[str] = None, - ) -> 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, - api_audience=api_audience, - ) - - 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 list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - Awaitable[functions.ListFunctionsResponse]]: - r"""Return a callable for the list functions method over gRPC. - - Returns a list of functions that belong to the - requested project. - - Returns: - Callable[[~.ListFunctionsRequest], - Awaitable[~.ListFunctionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_functions' not in self._stubs: - self._stubs['list_functions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', - request_serializer=functions.ListFunctionsRequest.serialize, - response_deserializer=functions.ListFunctionsResponse.deserialize, - ) - return self._stubs['list_functions'] - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - Awaitable[functions.CloudFunction]]: - r"""Return a callable for the get function method over gRPC. - - Returns a function with the given name from the - requested project. - - Returns: - Callable[[~.GetFunctionRequest], - Awaitable[~.CloudFunction]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_function' not in self._stubs: - self._stubs['get_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', - request_serializer=functions.GetFunctionRequest.serialize, - response_deserializer=functions.CloudFunction.deserialize, - ) - return self._stubs['get_function'] - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create function method over gRPC. - - Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - Returns: - Callable[[~.CreateFunctionRequest], - 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_function' not in self._stubs: - self._stubs['create_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', - request_serializer=functions.CreateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_function'] - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update function method over gRPC. - - Updates existing function. - - Returns: - Callable[[~.UpdateFunctionRequest], - 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_function' not in self._stubs: - self._stubs['update_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', - request_serializer=functions.UpdateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_function'] - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete function method over gRPC. - - Deletes a function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - Returns: - Callable[[~.DeleteFunctionRequest], - 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_function' not in self._stubs: - self._stubs['delete_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', - request_serializer=functions.DeleteFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_function'] - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - Awaitable[functions.CallFunctionResponse]]: - r"""Return a callable for the call function method over gRPC. - - Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - Returns: - Callable[[~.CallFunctionRequest], - Awaitable[~.CallFunctionResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'call_function' not in self._stubs: - self._stubs['call_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', - request_serializer=functions.CallFunctionRequest.serialize, - response_deserializer=functions.CallFunctionResponse.deserialize, - ) - return self._stubs['call_function'] - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - Awaitable[functions.GenerateUploadUrlResponse]]: - r"""Return a callable for the generate upload url method over gRPC. - - Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - Returns: - Callable[[~.GenerateUploadUrlRequest], - Awaitable[~.GenerateUploadUrlResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_upload_url' not in self._stubs: - self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', - request_serializer=functions.GenerateUploadUrlRequest.serialize, - response_deserializer=functions.GenerateUploadUrlResponse.deserialize, - ) - return self._stubs['generate_upload_url'] - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - Awaitable[functions.GenerateDownloadUrlResponse]]: - r"""Return a callable for the generate download url method over gRPC. - - Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - Returns: - Callable[[~.GenerateDownloadUrlRequest], - Awaitable[~.GenerateDownloadUrlResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_download_url' not in self._stubs: - self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', - request_serializer=functions.GenerateDownloadUrlRequest.serialize, - response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, - ) - return self._stubs['generate_download_url'] - - @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 on the specified - function. Replaces 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.functions.v1.CloudFunctionsService/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - Returns: - Callable[[~.GetIamPolicyRequest], - 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.functions.v1.CloudFunctionsService/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Returns: - Callable[[~.TestIamPermissionsRequest], - 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.functions.v1.CloudFunctionsService/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__ = ( - 'CloudFunctionsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py deleted file mode 100644 index b09e206..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py +++ /dev/null @@ -1,66 +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 .functions import ( - CallFunctionRequest, - CallFunctionResponse, - CloudFunction, - CreateFunctionRequest, - DeleteFunctionRequest, - EventTrigger, - FailurePolicy, - GenerateDownloadUrlRequest, - GenerateDownloadUrlResponse, - GenerateUploadUrlRequest, - GenerateUploadUrlResponse, - GetFunctionRequest, - HttpsTrigger, - ListFunctionsRequest, - ListFunctionsResponse, - SecretEnvVar, - SecretVolume, - SourceRepository, - UpdateFunctionRequest, - CloudFunctionStatus, -) -from .operations import ( - OperationMetadataV1, - OperationType, -) - -__all__ = ( - 'CallFunctionRequest', - 'CallFunctionResponse', - 'CloudFunction', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventTrigger', - 'FailurePolicy', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'HttpsTrigger', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'SecretEnvVar', - 'SecretVolume', - 'SourceRepository', - 'UpdateFunctionRequest', - 'CloudFunctionStatus', - 'OperationMetadataV1', - 'OperationType', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py deleted file mode 100644 index 844c961..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py +++ /dev/null @@ -1,1067 +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 duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.functions.v1', - manifest={ - 'CloudFunctionStatus', - 'CloudFunction', - 'SourceRepository', - 'HttpsTrigger', - 'EventTrigger', - 'FailurePolicy', - 'SecretEnvVar', - 'SecretVolume', - 'CreateFunctionRequest', - 'UpdateFunctionRequest', - 'GetFunctionRequest', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'DeleteFunctionRequest', - 'CallFunctionRequest', - 'CallFunctionResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - }, -) - - -class CloudFunctionStatus(proto.Enum): - r"""Describes the current stage of a deployment.""" - CLOUD_FUNCTION_STATUS_UNSPECIFIED = 0 - ACTIVE = 1 - OFFLINE = 2 - DEPLOY_IN_PROGRESS = 3 - DELETE_IN_PROGRESS = 4 - UNKNOWN = 5 - - -class CloudFunction(proto.Message): - r"""Describes a Cloud Function that contains user computation - executed in response to an event. It encapsulate function and - triggers configurations. - - 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): - A user-defined name of the function. Function names must be - unique globally and match pattern - ``projects/*/locations/*/functions/*`` - description (str): - User-provided description of a function. - source_archive_url (str): - The Google Cloud Storage URL, starting with ``gs://``, - pointing to the zip archive which contains the function. - - This field is a member of `oneof`_ ``source_code``. - source_repository (google.cloud.functions_v1.types.SourceRepository): - **Beta Feature** - - The source repository where a function is hosted. - - This field is a member of `oneof`_ ``source_code``. - source_upload_url (str): - The Google Cloud Storage signed URL used for source - uploading, generated by calling - [google.cloud.functions.v1.GenerateUploadUrl]. - - The signature is validated on write methods (Create, Update) - The signature is stripped from the Function object on read - methods (Get, List) - - This field is a member of `oneof`_ ``source_code``. - https_trigger (google.cloud.functions_v1.types.HttpsTrigger): - An HTTPS endpoint type of source that can be - triggered via URL. - - This field is a member of `oneof`_ ``trigger``. - event_trigger (google.cloud.functions_v1.types.EventTrigger): - A source that fires events in response to a - condition in another service. - - This field is a member of `oneof`_ ``trigger``. - status (google.cloud.functions_v1.types.CloudFunctionStatus): - Output only. Status of the function - deployment. - entry_point (str): - The name of the function (as defined in source code) that - will be executed. Defaults to the resource name suffix, if - not specified. For backward compatibility, if function with - given name is not found, then the system will try to use - function named "function". For Node.js this is name of a - function exported by the module specified in - ``source_location``. - runtime (str): - The runtime in which to run the function. Required when - deploying a new function, optional when updating an existing - function. For a complete list of possible choices, see the - ```gcloud`` command - reference `__. - timeout (google.protobuf.duration_pb2.Duration): - The function execution timeout. Execution is - considered failed and can be terminated if the - function is not completed at the end of the - timeout period. Defaults to 60 seconds. - available_memory_mb (int): - The amount of memory in MB available for a - function. Defaults to 256MB. - service_account_email (str): - The email of the function's service account. If empty, - defaults to ``{project_id}@appspot.gserviceaccount.com``. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last update timestamp of a - Cloud Function. - version_id (int): - Output only. The version identifier of the - Cloud Function. Each deployment attempt results - in a new version of a function being created. - labels (Mapping[str, str]): - Labels associated with this Cloud Function. - environment_variables (Mapping[str, str]): - Environment variables that shall be available - during function execution. - build_environment_variables (Mapping[str, str]): - Build environment variables that shall be - available during build time. - network (str): - The VPC Network that this cloud function can connect to. It - can be either the fully-qualified URI, or the short name of - the network resource. If the short network name is used, the - network must belong to the same project. Otherwise, it must - belong to a project within the same organization. The format - of this field is either - ``projects/{project}/global/networks/{network}`` or - ``{network}``, where ``{project}`` is a project id where the - network is defined, and ``{network}`` is the short name of - the network. - - This field is mutually exclusive with ``vpc_connector`` and - will be replaced by it. - - See `the VPC - documentation `__ - for more information on connecting Cloud projects. - max_instances (int): - The limit on the maximum number of function instances that - may coexist at a given time. - - In some cases, such as rapid traffic surges, Cloud Functions - may, for a short period of time, create more instances than - the specified max instances limit. If your function cannot - tolerate this temporary behavior, you may want to factor in - a safety margin and set a lower max instances value than - your function can tolerate. - - See the `Max - Instances `__ - Guide for more details. - min_instances (int): - A lower bound for the number function - instances that may coexist at a given time. - vpc_connector (str): - The VPC Network Connector that this cloud function can - connect to. It can be either the fully-qualified URI, or the - short name of the network connector resource. The format of - this field is ``projects/*/locations/*/connectors/*`` - - This field is mutually exclusive with ``network`` field and - will eventually replace it. - - See `the VPC - documentation `__ - for more information on connecting Cloud projects. - vpc_connector_egress_settings (google.cloud.functions_v1.types.CloudFunction.VpcConnectorEgressSettings): - The egress settings for the connector, - controlling what traffic is diverted through it. - ingress_settings (google.cloud.functions_v1.types.CloudFunction.IngressSettings): - The ingress settings for the function, - controlling what traffic can reach it. - kms_key_name (str): - Resource name of a KMS crypto key (managed by the user) used - to encrypt/decrypt function resources. - - It must match the pattern - ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. - - If specified, you must also provide an artifact registry - repository using the ``docker_repository`` field that was - created with the same KMS crypto key. - - The following service accounts need to be granted the role - 'Cloud KMS CryptoKey Encrypter/Decrypter - (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the - Key/KeyRing/Project/Organization (least access preferred). - - 1. Google Cloud Functions service account - (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - - Required to protect the function's image. - 2. Google Storage service account - (service-{project_number}@gs-project-accounts.iam.gserviceaccount.com) - - Required to protect the function's source code. If this - service account does not exist, deploying a function - without a KMS key or retrieving the service agent name - provisions it. For more information, see - https://cloud.google.com/storage/docs/projects#service-agents - and - https://cloud.google.com/storage/docs/getting-service-agent#gsutil. - - Google Cloud Functions delegates access to service agents to - protect function resources in internal projects that are not - accessible by the end user. - build_worker_pool (str): - Name of the Cloud Build Custom Worker Pool that should be - used to build the function. The format of this field is - ``projects/{project}/locations/{region}/workerPools/{workerPool}`` - where ``{project}`` and ``{region}`` are the project id and - region respectively where the worker pool is defined and - ``{workerPool}`` is the short name of the worker pool. - - If the project id is not the same as the function, then the - Cloud Functions Service Agent - (``service-@gcf-admin-robot.iam.gserviceaccount.com``) - must be granted the role Cloud Build Custom Workers Builder - (``roles/cloudbuild.customworkers.builder``) in the project. - build_id (str): - Output only. The Cloud Build ID of the latest - successful deployment of the function. - build_name (str): - Output only. The Cloud Build Name of the function - deployment. - ``projects//locations//builds/``. - secret_environment_variables (Sequence[google.cloud.functions_v1.types.SecretEnvVar]): - Secret environment variables configuration. - secret_volumes (Sequence[google.cloud.functions_v1.types.SecretVolume]): - Secret volumes configuration. - source_token (str): - Input only. An identifier for Firebase - function sources. Disclaimer: This field is only - supported for Firebase function deployments. - docker_repository (str): - User managed repository created in Artifact Registry - optionally with a customer managed encryption key. If - specified, deployments will use Artifact Registry. If - unspecified and the deployment is eligible to use Artifact - Registry, GCF will create and use a repository named - 'gcf-artifacts' for every deployed region. This is the - repository to which the function docker image will be pushed - after it is built by Cloud Build. - - It must match the pattern - ``projects/{project}/locations/{location}/repositories/{repository}``. - - Cross-project repositories are not supported. Cross-location - repositories are not supported. Repository format must be - 'DOCKER'. - docker_registry (google.cloud.functions_v1.types.CloudFunction.DockerRegistry): - Docker Registry to use for this deployment. - - If ``docker_repository`` field is specified, this field will - be automatically set as ``ARTIFACT_REGISTRY``. If - unspecified, it currently defaults to - ``CONTAINER_REGISTRY``. This field may be overridden by the - backend for eligible deployments. - """ - class VpcConnectorEgressSettings(proto.Enum): - r"""Available egress settings. - - This controls what traffic is diverted through the VPC Access - Connector resource. By default PRIVATE_RANGES_ONLY will be used. - """ - VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED = 0 - PRIVATE_RANGES_ONLY = 1 - ALL_TRAFFIC = 2 - - class IngressSettings(proto.Enum): - r"""Available ingress settings. - - This controls what traffic can reach the function. - - If unspecified, ALLOW_ALL will be used. - """ - INGRESS_SETTINGS_UNSPECIFIED = 0 - ALLOW_ALL = 1 - ALLOW_INTERNAL_ONLY = 2 - ALLOW_INTERNAL_AND_GCLB = 3 - - class DockerRegistry(proto.Enum): - r"""Docker Registry to use for storing function Docker images.""" - DOCKER_REGISTRY_UNSPECIFIED = 0 - CONTAINER_REGISTRY = 1 - ARTIFACT_REGISTRY = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - source_archive_url = proto.Field( - proto.STRING, - number=3, - oneof='source_code', - ) - source_repository = proto.Field( - proto.MESSAGE, - number=4, - oneof='source_code', - message='SourceRepository', - ) - source_upload_url = proto.Field( - proto.STRING, - number=16, - oneof='source_code', - ) - https_trigger = proto.Field( - proto.MESSAGE, - number=5, - oneof='trigger', - message='HttpsTrigger', - ) - event_trigger = proto.Field( - proto.MESSAGE, - number=6, - oneof='trigger', - message='EventTrigger', - ) - status = proto.Field( - proto.ENUM, - number=7, - enum='CloudFunctionStatus', - ) - entry_point = proto.Field( - proto.STRING, - number=8, - ) - runtime = proto.Field( - proto.STRING, - number=19, - ) - timeout = proto.Field( - proto.MESSAGE, - number=9, - message=duration_pb2.Duration, - ) - available_memory_mb = proto.Field( - proto.INT32, - number=10, - ) - service_account_email = proto.Field( - proto.STRING, - number=11, - ) - update_time = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - version_id = proto.Field( - proto.INT64, - number=14, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=15, - ) - environment_variables = proto.MapField( - proto.STRING, - proto.STRING, - number=17, - ) - build_environment_variables = proto.MapField( - proto.STRING, - proto.STRING, - number=28, - ) - network = proto.Field( - proto.STRING, - number=18, - ) - max_instances = proto.Field( - proto.INT32, - number=20, - ) - min_instances = proto.Field( - proto.INT32, - number=32, - ) - vpc_connector = proto.Field( - proto.STRING, - number=22, - ) - vpc_connector_egress_settings = proto.Field( - proto.ENUM, - number=23, - enum=VpcConnectorEgressSettings, - ) - ingress_settings = proto.Field( - proto.ENUM, - number=24, - enum=IngressSettings, - ) - kms_key_name = proto.Field( - proto.STRING, - number=25, - ) - build_worker_pool = proto.Field( - proto.STRING, - number=26, - ) - build_id = proto.Field( - proto.STRING, - number=27, - ) - build_name = proto.Field( - proto.STRING, - number=33, - ) - secret_environment_variables = proto.RepeatedField( - proto.MESSAGE, - number=29, - message='SecretEnvVar', - ) - secret_volumes = proto.RepeatedField( - proto.MESSAGE, - number=30, - message='SecretVolume', - ) - source_token = proto.Field( - proto.STRING, - number=31, - ) - docker_repository = proto.Field( - proto.STRING, - number=34, - ) - docker_registry = proto.Field( - proto.ENUM, - number=35, - enum=DockerRegistry, - ) - - -class SourceRepository(proto.Message): - r"""Describes SourceRepository, used to represent parameters - related to source repository where a function is hosted. - - Attributes: - url (str): - The URL pointing to the hosted repository where the function - is defined. There are supported Cloud Source Repository URLs - in the following formats: - - To refer to a specific commit: - ``https://source.developers.google.com/projects/*/repos/*/revisions/*/paths/*`` - To refer to a moveable alias (branch): - ``https://source.developers.google.com/projects/*/repos/*/moveable-aliases/*/paths/*`` - In particular, to refer to HEAD use ``master`` moveable - alias. To refer to a specific fixed alias (tag): - ``https://source.developers.google.com/projects/*/repos/*/fixed-aliases/*/paths/*`` - - You may omit ``paths/*`` if you want to use the main - directory. - deployed_url (str): - Output only. The URL pointing to the hosted - repository where the function were defined at - the time of deployment. It always points to a - specific commit in the format described above. - """ - - url = proto.Field( - proto.STRING, - number=1, - ) - deployed_url = proto.Field( - proto.STRING, - number=2, - ) - - -class HttpsTrigger(proto.Message): - r"""Describes HttpsTrigger, could be used to connect web hooks to - function. - - Attributes: - url (str): - Output only. The deployed url for the - function. - security_level (google.cloud.functions_v1.types.HttpsTrigger.SecurityLevel): - The security level for the function. - """ - class SecurityLevel(proto.Enum): - r"""Available security level settings. - - This controls the methods to enforce security (HTTPS) on a URL. - - If unspecified, SECURE_OPTIONAL will be used. - """ - SECURITY_LEVEL_UNSPECIFIED = 0 - SECURE_ALWAYS = 1 - SECURE_OPTIONAL = 2 - - url = proto.Field( - proto.STRING, - number=1, - ) - security_level = proto.Field( - proto.ENUM, - number=2, - enum=SecurityLevel, - ) - - -class EventTrigger(proto.Message): - r"""Describes EventTrigger, used to request events be sent from - another service. - - Attributes: - event_type (str): - Required. The type of event to observe. For example: - ``providers/cloud.storage/eventTypes/object.change`` and - ``providers/cloud.pubsub/eventTypes/topic.publish``. - - Event types match pattern ``providers/*/eventTypes/*.*``. - The pattern contains: - - 1. namespace: For example, ``cloud.storage`` and - ``google.firebase.analytics``. - 2. resource type: The type of resource on which event - occurs. For example, the Google Cloud Storage API - includes the type ``object``. - 3. action: The action that generates the event. For example, - action for a Google Cloud Storage Object is 'change'. - These parts are lower case. - resource (str): - Required. The resource(s) from which to observe events, for - example, ``projects/_/buckets/myBucket``. - - Not all syntactically correct values are accepted by all - services. For example: - - 1. The authorization model must support it. Google Cloud - Functions only allows EventTriggers to be deployed that - observe resources in the same project as the - ``CloudFunction``. - 2. The resource type must match the pattern expected for an - ``event_type``. For example, an ``EventTrigger`` that has - an ``event_type`` of "google.pubsub.topic.publish" should - have a resource that matches Google Cloud Pub/Sub topics. - - Additionally, some services may support short names when - creating an ``EventTrigger``. These will always be returned - in the normalized "long" format. - - See each *service's* documentation for supported formats. - service (str): - The hostname of the service that should be observed. - - If no string is provided, the default service implementing - the API will be used. For example, - ``storage.googleapis.com`` is the default for all event - types in the ``google.storage`` namespace. - failure_policy (google.cloud.functions_v1.types.FailurePolicy): - Specifies policy for failed executions. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - resource = proto.Field( - proto.STRING, - number=2, - ) - service = proto.Field( - proto.STRING, - number=3, - ) - failure_policy = proto.Field( - proto.MESSAGE, - number=5, - message='FailurePolicy', - ) - - -class FailurePolicy(proto.Message): - r"""Describes the policy in case of function's execution failure. - If empty, then defaults to ignoring failures (i.e. not retrying - them). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - retry (google.cloud.functions_v1.types.FailurePolicy.Retry): - If specified, then the function will be - retried in case of a failure. - - This field is a member of `oneof`_ ``action``. - """ - - class Retry(proto.Message): - r"""Describes the retry policy in case of function's execution - failure. A function execution will be retried on any failure. A - failed execution will be retried up to 7 days with an - exponential backoff (capped at 10 seconds). - Retried execution is charged as any other execution. - - """ - - retry = proto.Field( - proto.MESSAGE, - number=1, - oneof='action', - message=Retry, - ) - - -class SecretEnvVar(proto.Message): - r"""Configuration for a secret environment variable. It has the - information necessary to fetch the secret value from secret - manager and expose it as an environment variable. - - Attributes: - key (str): - Name of the environment variable. - project_id (str): - Project identifier (preferrably project - number but can also be the project ID) of the - project that contains the secret. If not set, it - will be populated with the function's project - assuming that the secret exists in the same - project as of the function. - secret (str): - Name of the secret in secret manager (not the - full resource name). - version (str): - Version of the secret (version number or the - string 'latest'). It is recommended to use a - numeric version for secret environment variables - as any updates to the secret value is not - reflected until new instances start. - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - project_id = proto.Field( - proto.STRING, - number=2, - ) - secret = proto.Field( - proto.STRING, - number=3, - ) - version = proto.Field( - proto.STRING, - number=4, - ) - - -class SecretVolume(proto.Message): - r"""Configuration for a secret volume. It has the information - necessary to fetch the secret value from secret manager and make - it available as files mounted at the requested paths within the - application container. Secret value is not a part of the - configuration. Every filesystem read operation performs a lookup - in secret manager to retrieve the secret value. - - Attributes: - mount_path (str): - The path within the container to mount the secret volume. - For example, setting the mount_path as ``/etc/secrets`` - would mount the secret value files under the - ``/etc/secrets`` directory. This directory will also be - completely shadowed and unavailable to mount any other - secrets. - - Recommended mount paths: /etc/secrets Restricted mount - paths: /cloudsql, /dev/log, /pod, /proc, /var/log - project_id (str): - Project identifier (preferrably project - number but can also be the project ID) of the - project that contains the secret. If not set, it - will be populated with the function's project - assuming that the secret exists in the same - project as of the function. - secret (str): - Name of the secret in secret manager (not the - full resource name). - versions (Sequence[google.cloud.functions_v1.types.SecretVolume.SecretVersion]): - List of secret versions to mount for this secret. If empty, - the ``latest`` version of the secret will be made available - in a file named after the secret under the mount point. - """ - - class SecretVersion(proto.Message): - r"""Configuration for a single version. - - Attributes: - version (str): - Version of the secret (version number or the string - 'latest'). It is preferrable to use ``latest`` version with - secret volumes as secret value changes are reflected - immediately. - path (str): - Relative path of the file under the mount path where the - secret value for this version will be fetched and made - available. For example, setting the mount_path as - '/etc/secrets' and path as ``/secret_foo`` would mount the - secret value file at ``/etc/secrets/secret_foo``. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - path = proto.Field( - proto.STRING, - number=2, - ) - - mount_path = proto.Field( - proto.STRING, - number=1, - ) - project_id = proto.Field( - proto.STRING, - number=2, - ) - secret = proto.Field( - proto.STRING, - number=3, - ) - versions = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=SecretVersion, - ) - - -class CreateFunctionRequest(proto.Message): - r"""Request for the ``CreateFunction`` method. - - Attributes: - location (str): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - function (google.cloud.functions_v1.types.CloudFunction): - Required. Function to be created. - """ - - location = proto.Field( - proto.STRING, - number=1, - ) - function = proto.Field( - proto.MESSAGE, - number=2, - message='CloudFunction', - ) - - -class UpdateFunctionRequest(proto.Message): - r"""Request for the ``UpdateFunction`` method. - - Attributes: - function (google.cloud.functions_v1.types.CloudFunction): - Required. New version of the function. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields in ``CloudFunction`` that have - to be updated. - """ - - function = proto.Field( - proto.MESSAGE, - number=1, - message='CloudFunction', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetFunctionRequest(proto.Message): - r"""Request for the ``GetFunction`` method. - - Attributes: - name (str): - Required. The name of the function which - details should be obtained. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFunctionsRequest(proto.Message): - r"""Request for the ``ListFunctions`` method. - - Attributes: - parent (str): - The project and location from which the function should be - listed, specified in the format ``projects/*/locations/*`` - If you want to list functions in all locations, use "-" in - place of a location. When listing functions in all - locations, if one or more location(s) are unreachable, the - response will contain functions from all reachable locations - along with the names of any unreachable locations. - page_size (int): - Maximum number of functions to return per - call. - page_token (str): - The value returned by the last ``ListFunctionsResponse``; - indicates that this is a continuation of a prior - ``ListFunctions`` call, and that the system should return - the next page of data. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListFunctionsResponse(proto.Message): - r"""Response for the ``ListFunctions`` method. - - Attributes: - functions (Sequence[google.cloud.functions_v1.types.CloudFunction]): - The functions that match the request. - next_page_token (str): - If not empty, indicates that there may be more functions - that match the request; this value should be passed in a new - [google.cloud.functions.v1.ListFunctionsRequest][google.cloud.functions.v1.ListFunctionsRequest] - to get more functions. - unreachable (Sequence[str]): - Locations that could not be reached. The - response does not include any functions from - these locations. - """ - - @property - def raw_page(self): - return self - - functions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='CloudFunction', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - unreachable = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class DeleteFunctionRequest(proto.Message): - r"""Request for the ``DeleteFunction`` method. - - Attributes: - name (str): - Required. The name of the function which - should be deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CallFunctionRequest(proto.Message): - r"""Request for the ``CallFunction`` method. - - Attributes: - name (str): - Required. The name of the function to be - called. - data (str): - Required. Input to be passed to the function. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - data = proto.Field( - proto.STRING, - number=2, - ) - - -class CallFunctionResponse(proto.Message): - r"""Response of ``CallFunction`` method. - - Attributes: - execution_id (str): - Execution id of function invocation. - result (str): - Result populated for successful execution of - synchronous function. Will not be populated if - function does not return a result through - context. - error (str): - Either system or user-function generated - error. Set if execution was not successful. - """ - - execution_id = proto.Field( - proto.STRING, - number=1, - ) - result = proto.Field( - proto.STRING, - number=2, - ) - error = proto.Field( - proto.STRING, - number=3, - ) - - -class GenerateUploadUrlRequest(proto.Message): - r"""Request of ``GenerateSourceUploadUrl`` method. - - Attributes: - parent (str): - The project and location in which the Google Cloud Storage - signed URL should be generated, specified in the format - ``projects/*/locations/*``. - kms_key_name (str): - Resource name of a KMS crypto key (managed by the user) used - to encrypt/decrypt function source code objects in staging - Cloud Storage buckets. When you generate an upload url and - upload your source code, it gets copied to a staging Cloud - Storage bucket in an internal regional project. The source - code is then copied to a versioned directory in the sources - bucket in the consumer project during the function - deployment. - - It must match the pattern - ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. - - The Google Cloud Functions service account - (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - must be granted the role 'Cloud KMS CryptoKey - Encrypter/Decrypter - (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the - Key/KeyRing/Project/Organization (least access preferred). - GCF will delegate access to the Google Storage service - account in the internal project. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - kms_key_name = proto.Field( - proto.STRING, - number=2, - ) - - -class GenerateUploadUrlResponse(proto.Message): - r"""Response of ``GenerateSourceUploadUrl`` method. - - Attributes: - upload_url (str): - The generated Google Cloud Storage signed URL - that should be used for a function source code - upload. The uploaded file should be a zip - archive which contains a function. - """ - - upload_url = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateDownloadUrlRequest(proto.Message): - r"""Request of ``GenerateDownloadUrl`` method. - - Attributes: - name (str): - The name of function for which source code - Google Cloud Storage signed URL should be - generated. - version_id (int): - The optional version of function. If not set, - default, current version is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - version_id = proto.Field( - proto.UINT64, - number=2, - ) - - -class GenerateDownloadUrlResponse(proto.Message): - r"""Response of ``GenerateDownloadUrl`` method. - - Attributes: - download_url (str): - The generated Google Cloud Storage signed URL - that should be used for function source code - download. - """ - - download_url = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py deleted file mode 100644 index ab59796..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py +++ /dev/null @@ -1,108 +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 any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.functions.v1', - manifest={ - 'OperationType', - 'OperationMetadataV1', - }, -) - - -class OperationType(proto.Enum): - r"""A type of an operation.""" - OPERATION_UNSPECIFIED = 0 - CREATE_FUNCTION = 1 - UPDATE_FUNCTION = 2 - DELETE_FUNCTION = 3 - - -class OperationMetadataV1(proto.Message): - r"""Metadata describing an [Operation][google.longrunning.Operation] - - Attributes: - target (str): - Target of the operation - for example - ``projects/project-1/locations/region-1/functions/function-1`` - type_ (google.cloud.functions_v1.types.OperationType): - Type of operation. - request (google.protobuf.any_pb2.Any): - The original request that started the - operation. - version_id (int): - Version id of the function created or updated - by an API call. This field is only populated for - Create and Update operations. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update timestamp of the operation. - build_id (str): - The Cloud Build ID of the function created or - updated by an API call. This field is only - populated for Create and Update operations. - source_token (str): - An identifier for Firebase function sources. - Disclaimer: This field is only supported for - Firebase function deployments. - build_name (str): - The Cloud Build Name of the function deployment. This field - is only populated for Create and Update operations. - ``projects//locations//builds/``. - """ - - target = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - enum='OperationType', - ) - request = proto.Field( - proto.MESSAGE, - number=3, - message=any_pb2.Any, - ) - version_id = proto.Field( - proto.INT64, - number=4, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - build_id = proto.Field( - proto.STRING, - number=6, - ) - source_token = proto.Field( - proto.STRING, - number=7, - ) - build_name = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 38940e8..0000000 --- a/owl-bot-staging/v1/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', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/functions_v1/', - '--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/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py deleted file mode 100644 index f6b67dc..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] -from google.cloud import functions_v1 - - -async def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = await client.call_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py deleted file mode 100644 index 7cddbe7..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] -from google.cloud import functions_v1 - - -def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = client.call_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py deleted file mode 100644 index dd6b621..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py +++ /dev/null @@ -1,53 +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 CreateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] -from google.cloud import functions_v1 - - -async def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py deleted file mode 100644 index 117d443..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py +++ /dev/null @@ -1,53 +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 CreateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] -from google.cloud import functions_v1 - - -def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py deleted file mode 100644 index 3051534..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] -from google.cloud import functions_v1 - - -async def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py deleted file mode 100644 index 2262e7b..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] -from google.cloud import functions_v1 - - -def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py deleted file mode 100644 index 30f6889..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py +++ /dev/null @@ -1,44 +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 GenerateDownloadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] -from google.cloud import functions_v1 - - -async def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = await client.generate_download_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py deleted file mode 100644 index fbc886f..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py +++ /dev/null @@ -1,44 +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 GenerateDownloadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] -from google.cloud import functions_v1 - - -def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = client.generate_download_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py deleted file mode 100644 index 6b19431..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py +++ /dev/null @@ -1,44 +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 GenerateUploadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] -from google.cloud import functions_v1 - - -async def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = await client.generate_upload_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py deleted file mode 100644 index 6e9590a..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py +++ /dev/null @@ -1,44 +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 GenerateUploadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] -from google.cloud import functions_v1 - - -def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = client.generate_upload_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py deleted file mode 100644 index f89b7da..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] -from google.cloud import functions_v1 - - -async def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py deleted file mode 100644 index 761c41d..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] -from google.cloud import functions_v1 - - -def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = client.get_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py deleted file mode 100644 index 09d1b8a..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py deleted file mode 100644 index eafe7b7..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py deleted file mode 100644 index 9a3cd36..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] -from google.cloud import functions_v1 - - -async def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py deleted file mode 100644 index 98b3760..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] -from google.cloud import functions_v1 - - -def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py deleted file mode 100644 index 2d1128e..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py deleted file mode 100644 index b8b14ab..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py deleted file mode 100644 index 936744f..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py +++ /dev/null @@ -1,47 +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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py deleted file mode 100644 index c5766f3..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py +++ /dev/null @@ -1,47 +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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py deleted file mode 100644 index 4863198..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py +++ /dev/null @@ -1,52 +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 UpdateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] -from google.cloud import functions_v1 - - -async def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py deleted file mode 100644 index 11809c3..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py +++ /dev/null @@ -1,52 +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 UpdateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] -from google.cloud import functions_v1 - - -def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json deleted file mode 100644 index 9c991cf..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json +++ /dev/null @@ -1,1753 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.functions.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-functions" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.call_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CallFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CallFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", - "shortName": "call_function" - }, - "description": "Sample for CallFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.call_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CallFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CallFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", - "shortName": "call_function" - }, - "description": "Sample for CallFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.create_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CreateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CreateFunctionRequest" - }, - { - "name": "location", - "type": "str" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_function" - }, - "description": "Sample for CreateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.create_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CreateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CreateFunctionRequest" - }, - { - "name": "location", - "type": "str" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_function" - }, - "description": "Sample for CreateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.delete_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "DeleteFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_function" - }, - "description": "Sample for DeleteFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.delete_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "DeleteFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_function" - }, - "description": "Sample for DeleteFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_download_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateDownloadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", - "shortName": "generate_download_url" - }, - "description": "Sample for GenerateDownloadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_download_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateDownloadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", - "shortName": "generate_download_url" - }, - "description": "Sample for GenerateDownloadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_upload_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateUploadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", - "shortName": "generate_upload_url" - }, - "description": "Sample for GenerateUploadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_upload_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateUploadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", - "shortName": "generate_upload_url" - }, - "description": "Sample for GenerateUploadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GetFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CloudFunction", - "shortName": "get_function" - }, - "description": "Sample for GetFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GetFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CloudFunction", - "shortName": "get_function" - }, - "description": "Sample for GetFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.list_functions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "ListFunctions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.ListFunctionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager", - "shortName": "list_functions" - }, - "description": "Sample for ListFunctions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.list_functions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "ListFunctions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.ListFunctionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager", - "shortName": "list_functions" - }, - "description": "Sample for ListFunctions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.set_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 43, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 44, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 43, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 44, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.update_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "UpdateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_function" - }, - "description": "Sample for UpdateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.update_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "UpdateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_function" - }, - "description": "Sample for UpdateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py deleted file mode 100644 index 6dc057c..0000000 --- a/owl-bot-staging/v1/scripts/fixup_functions_v1_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 functionsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'call_function': ('name', 'data', ), - 'create_function': ('location', 'function', ), - 'delete_function': ('name', ), - 'generate_download_url': ('name', 'version_id', ), - 'generate_upload_url': ('parent', 'kms_key_name', ), - 'get_function': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'list_functions': ('parent', 'page_size', 'page_token', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_function': ('function', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=functionsCallTransformer(), -): - """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 functions client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index 820b19a..0000000 --- a/owl-bot-staging/v1/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-functions', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-functions", - 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] >= 2.8.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.4, < 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/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/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/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/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/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/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/v1/tests/unit/gapic/functions_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__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/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py deleted file mode 100644 index 86b090e..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py +++ /dev/null @@ -1,3681 +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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import 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.functions_v1.services.cloud_functions_service import CloudFunctionsServiceAsyncClient -from google.cloud.functions_v1.services.cloud_functions_service import CloudFunctionsServiceClient -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.services.cloud_functions_service import transports -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -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 CloudFunctionsServiceClient._get_default_mtls_endpoint(None) is None - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CloudFunctionsServiceClient, "grpc"), - (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CloudFunctionsServiceClient, "grpc"), - (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:443' - ) - - -def test_cloud_functions_service_client_get_transport_class(): - transport = CloudFunctionsServiceClient.get_transport_class() - available_transports = [ - transports.CloudFunctionsServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CloudFunctionsServiceClient.get_transport_class("grpc") - assert transport == transports.CloudFunctionsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) -def test_cloud_functions_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CloudFunctionsServiceClient, '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(CloudFunctionsServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - 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, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "true"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "false"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_cloud_functions_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CloudFunctionsServiceClient, CloudFunctionsServiceAsyncClient -]) -@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) -def test_cloud_functions_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_cloud_functions_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_cloud_functions_service_client_client_options_from_dict(): - with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CloudFunctionsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_cloud_functions_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudfunctions.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="cloudfunctions.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - functions.ListFunctionsRequest, - dict, -]) -def test_list_functions(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_functions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.ListFunctionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFunctionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_functions_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 = CloudFunctionsServiceClient( - 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_functions), - '__call__') as call: - client.list_functions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - -@pytest.mark.asyncio -async def test_list_functions_async(transport: str = 'grpc_asyncio', request_type=functions.ListFunctionsRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_functions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFunctionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_functions_async_from_dict(): - await test_list_functions_async(request_type=dict) - - -def test_list_functions_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.ListFunctionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: - call.return_value = functions.ListFunctionsResponse() - client.list_functions(request) - - # Establish that the 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_functions_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.ListFunctionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse()) - await client.list_functions(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_functions_pager(transport_name: str = "grpc"): - client = CloudFunctionsServiceClient( - 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_functions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_functions(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, functions.CloudFunction) - for i in results) -def test_list_functions_pages(transport_name: str = "grpc"): - client = CloudFunctionsServiceClient( - 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_functions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - pages = list(client.list_functions(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_functions_async_pager(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_functions(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, functions.CloudFunction) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_functions_async_pages(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_functions(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", [ - functions.GetFunctionRequest, - dict, -]) -def test_get_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CloudFunction( - name='name_value', - description='description_value', - status=functions.CloudFunctionStatus.ACTIVE, - entry_point='entry_point_value', - runtime='runtime_value', - available_memory_mb=1991, - service_account_email='service_account_email_value', - version_id=1074, - network='network_value', - max_instances=1389, - min_instances=1387, - vpc_connector='vpc_connector_value', - vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, - ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, - kms_key_name='kms_key_name_value', - build_worker_pool='build_worker_pool_value', - build_id='build_id_value', - build_name='build_name_value', - source_token='source_token_value', - docker_repository='docker_repository_value', - docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, - source_archive_url='source_archive_url_value', - https_trigger=functions.HttpsTrigger(url='url_value'), - ) - response = client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CloudFunction) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.status == functions.CloudFunctionStatus.ACTIVE - assert response.entry_point == 'entry_point_value' - assert response.runtime == 'runtime_value' - assert response.available_memory_mb == 1991 - assert response.service_account_email == 'service_account_email_value' - assert response.version_id == 1074 - assert response.network == 'network_value' - assert response.max_instances == 1389 - assert response.min_instances == 1387 - assert response.vpc_connector == 'vpc_connector_value' - assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY - assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL - assert response.kms_key_name == 'kms_key_name_value' - assert response.build_worker_pool == 'build_worker_pool_value' - assert response.build_id == 'build_id_value' - assert response.build_name == 'build_name_value' - assert response.source_token == 'source_token_value' - assert response.docker_repository == 'docker_repository_value' - assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY - - -def test_get_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.get_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - -@pytest.mark.asyncio -async def test_get_function_async(transport: str = 'grpc_asyncio', request_type=functions.GetFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction( - name='name_value', - description='description_value', - status=functions.CloudFunctionStatus.ACTIVE, - entry_point='entry_point_value', - runtime='runtime_value', - available_memory_mb=1991, - service_account_email='service_account_email_value', - version_id=1074, - network='network_value', - max_instances=1389, - min_instances=1387, - vpc_connector='vpc_connector_value', - vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, - ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, - kms_key_name='kms_key_name_value', - build_worker_pool='build_worker_pool_value', - build_id='build_id_value', - build_name='build_name_value', - source_token='source_token_value', - docker_repository='docker_repository_value', - docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, - )) - response = await client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CloudFunction) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.status == functions.CloudFunctionStatus.ACTIVE - assert response.entry_point == 'entry_point_value' - assert response.runtime == 'runtime_value' - assert response.available_memory_mb == 1991 - assert response.service_account_email == 'service_account_email_value' - assert response.version_id == 1074 - assert response.network == 'network_value' - assert response.max_instances == 1389 - assert response.min_instances == 1387 - assert response.vpc_connector == 'vpc_connector_value' - assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY - assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL - assert response.kms_key_name == 'kms_key_name_value' - assert response.build_worker_pool == 'build_worker_pool_value' - assert response.build_id == 'build_id_value' - assert response.build_name == 'build_name_value' - assert response.source_token == 'source_token_value' - assert response.docker_repository == 'docker_repository_value' - assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY - - -@pytest.mark.asyncio -async def test_get_function_async_from_dict(): - await test_get_function_async(request_type=dict) - - -def test_get_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GetFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - call.return_value = functions.CloudFunction() - client.get_function(request) - - # Establish that the 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_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GetFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) - await client.get_function(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_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CloudFunction() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_function( - 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_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.GetFunctionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CloudFunction() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_function( - 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_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.GetFunctionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.CreateFunctionRequest, - dict, -]) -def test_create_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.create_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - -@pytest.mark.asyncio -async def test_create_function_async(transport: str = 'grpc_asyncio', request_type=functions.CreateFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__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_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_function_async_from_dict(): - await test_create_function_async(request_type=dict) - - -def test_create_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CreateFunctionRequest() - - request.location = 'location_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_function(request) - - # Establish that the 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', - 'location=location_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CreateFunctionRequest() - - request.location = 'location_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_function(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', - 'location=location_value', - ) in kw['metadata'] - - -def test_create_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__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_function( - location='location_value', - function=functions.CloudFunction(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].location - mock_val = 'location_value' - assert arg == mock_val - arg = args[0].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - - -def test_create_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.CreateFunctionRequest(), - location='location_value', - function=functions.CloudFunction(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__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_function( - location='location_value', - function=functions.CloudFunction(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].location - mock_val = 'location_value' - assert arg == mock_val - arg = args[0].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.CreateFunctionRequest(), - location='location_value', - function=functions.CloudFunction(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - functions.UpdateFunctionRequest, - dict, -]) -def test_update_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.update_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - -@pytest.mark.asyncio -async def test_update_function_async(transport: str = 'grpc_asyncio', request_type=functions.UpdateFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__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_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_function_async_from_dict(): - await test_update_function_async(request_type=dict) - - -def test_update_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.UpdateFunctionRequest() - - request.function.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_function(request) - - # Establish that the 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', - 'function.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.UpdateFunctionRequest() - - request.function.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_function(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', - 'function.name=name_value', - ) in kw['metadata'] - - -def test_update_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__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_function( - function=functions.CloudFunction(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].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - - -def test_update_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.UpdateFunctionRequest(), - function=functions.CloudFunction(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__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_function( - function=functions.CloudFunction(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].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.UpdateFunctionRequest(), - function=functions.CloudFunction(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - functions.DeleteFunctionRequest, - dict, -]) -def test_delete_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.delete_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - -@pytest.mark.asyncio -async def test_delete_function_async(transport: str = 'grpc_asyncio', request_type=functions.DeleteFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__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_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_function_async_from_dict(): - await test_delete_function_async(request_type=dict) - - -def test_delete_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.DeleteFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_function(request) - - # Establish that the 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_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.DeleteFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_function(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_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__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_function( - 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_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.DeleteFunctionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__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_function( - 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_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.DeleteFunctionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.CallFunctionRequest, - dict, -]) -def test_call_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse( - execution_id='execution_id_value', - result='result_value', - error='error_value', - ) - response = client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CallFunctionResponse) - assert response.execution_id == 'execution_id_value' - assert response.result == 'result_value' - assert response.error == 'error_value' - - -def test_call_function_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 = CloudFunctionsServiceClient( - 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.call_function), - '__call__') as call: - client.call_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - -@pytest.mark.asyncio -async def test_call_function_async(transport: str = 'grpc_asyncio', request_type=functions.CallFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse( - execution_id='execution_id_value', - result='result_value', - error='error_value', - )) - response = await client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CallFunctionResponse) - assert response.execution_id == 'execution_id_value' - assert response.result == 'result_value' - assert response.error == 'error_value' - - -@pytest.mark.asyncio -async def test_call_function_async_from_dict(): - await test_call_function_async(request_type=dict) - - -def test_call_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CallFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - call.return_value = functions.CallFunctionResponse() - client.call_function(request) - - # Establish that the 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_call_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CallFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) - await client.call_function(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_call_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.call_function( - name='name_value', - data='data_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 - arg = args[0].data - mock_val = 'data_value' - assert arg == mock_val - - -def test_call_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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.call_function( - functions.CallFunctionRequest(), - name='name_value', - data='data_value', - ) - -@pytest.mark.asyncio -async def test_call_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.call_function( - name='name_value', - data='data_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 - arg = args[0].data - mock_val = 'data_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_call_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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.call_function( - functions.CallFunctionRequest(), - name='name_value', - data='data_value', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateUploadUrlRequest, - dict, -]) -def test_generate_upload_url(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.GenerateUploadUrlResponse( - upload_url='upload_url_value', - ) - response = client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateUploadUrlResponse) - assert response.upload_url == 'upload_url_value' - - -def test_generate_upload_url_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 = CloudFunctionsServiceClient( - 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.generate_upload_url), - '__call__') as call: - client.generate_upload_url() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - -@pytest.mark.asyncio -async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateUploadUrlRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse( - upload_url='upload_url_value', - )) - response = await client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateUploadUrlResponse) - assert response.upload_url == 'upload_url_value' - - -@pytest.mark.asyncio -async def test_generate_upload_url_async_from_dict(): - await test_generate_upload_url_async(request_type=dict) - - -def test_generate_upload_url_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateUploadUrlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - call.return_value = functions.GenerateUploadUrlResponse() - client.generate_upload_url(request) - - # Establish that the 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_generate_upload_url_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateUploadUrlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse()) - await client.generate_upload_url(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'] - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateDownloadUrlRequest, - dict, -]) -def test_generate_download_url(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.GenerateDownloadUrlResponse( - download_url='download_url_value', - ) - response = client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateDownloadUrlResponse) - assert response.download_url == 'download_url_value' - - -def test_generate_download_url_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 = CloudFunctionsServiceClient( - 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.generate_download_url), - '__call__') as call: - client.generate_download_url() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - -@pytest.mark.asyncio -async def test_generate_download_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateDownloadUrlRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse( - download_url='download_url_value', - )) - response = await client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateDownloadUrlResponse) - assert response.download_url == 'download_url_value' - - -@pytest.mark.asyncio -async def test_generate_download_url_async_from_dict(): - await test_generate_download_url_async(request_type=dict) - - -def test_generate_download_url_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateDownloadUrlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - call.return_value = functions.GenerateDownloadUrlResponse() - client.generate_download_url(request) - - # Establish that the 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_generate_download_url_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateDownloadUrlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse()) - await client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceClient( - 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.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceClient( - 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.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceClient( - 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.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CloudFunctionsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, -]) -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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CloudFunctionsServiceGrpcTransport, - ) - -def test_cloud_functions_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CloudFunctionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_cloud_functions_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CloudFunctionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_functions', - 'get_function', - 'create_function', - 'update_function', - 'delete_function', - 'call_function', - 'generate_upload_url', - 'generate_download_url', - 'set_iam_policy', - 'get_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_cloud_functions_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudFunctionsServiceTransport( - 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_cloud_functions_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudFunctionsServiceTransport() - adc.assert_called_once() - - -def test_cloud_functions_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CloudFunctionsServiceClient() - 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.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, - ], -) -def test_cloud_functions_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, - ], -) -def test_cloud_functions_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CloudFunctionsServiceGrpcTransport, grpc_helpers), - (transports.CloudFunctionsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_cloud_functions_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "cloudfunctions.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="cloudfunctions.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_cloud_functions_service_host_no_port(transport_name): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_cloud_functions_service_host_with_port(transport_name): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:8000' - ) - -def test_cloud_functions_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CloudFunctionsServiceGrpcTransport( - 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_cloud_functions_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( - 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.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_cloud_functions_service_grpc_lro_client(): - client = CloudFunctionsServiceClient( - 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_cloud_functions_service_grpc_lro_async_client(): - client = CloudFunctionsServiceAsyncClient( - 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_cloud_function_path(): - project = "squid" - location = "clam" - function = "whelk" - expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) - actual = CloudFunctionsServiceClient.cloud_function_path(project, location, function) - assert expected == actual - - -def test_parse_cloud_function_path(): - expected = { - "project": "octopus", - "location": "oyster", - "function": "nudibranch", - } - path = CloudFunctionsServiceClient.cloud_function_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_cloud_function_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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_crypto_key_path(path) - assert expected == actual - -def test_repository_path(): - project = "whelk" - location = "octopus" - repository = "oyster" - expected = "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) - actual = CloudFunctionsServiceClient.repository_path(project, location, repository) - assert expected == actual - - -def test_parse_repository_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "repository": "mussel", - } - path = CloudFunctionsServiceClient.repository_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_repository_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CloudFunctionsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = CloudFunctionsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = CloudFunctionsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = CloudFunctionsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CloudFunctionsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = CloudFunctionsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = CloudFunctionsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = CloudFunctionsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CloudFunctionsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = CloudFunctionsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.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.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CloudFunctionsServiceClient.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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceClient( - 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", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport), -]) -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, - api_audience=None, - ) diff --git a/tests/unit/gapic/functions_v1/test_cloud_functions_service.py b/tests/unit/gapic/functions_v1/test_cloud_functions_service.py index 754e700..6606e10 100644 --- a/tests/unit/gapic/functions_v1/test_cloud_functions_service.py +++ b/tests/unit/gapic/functions_v1/test_cloud_functions_service.py @@ -3407,7 +3407,6 @@ def test_cloud_functions_service_transport_auth_adc(transport_class): [ transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport, - transports.CloudFunctionsServiceRestTransport, ], ) def test_cloud_functions_service_transport_auth_gdch_credentials(transport_class): From e7d2f3a234677298697886ea65c29b35364580eb Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 6 Jul 2022 20:48:32 +0000 Subject: [PATCH 05/16] feat: generating GAPIC libraries for Google Cloud Functions v2beta PiperOrigin-RevId: 459309277 Source-Link: https://github.com/googleapis/googleapis/commit/2844793f71df766526ceeee8a35c90d7ac101fbe Source-Link: https://github.com/googleapis/googleapis-gen/commit/319987cc0e8789a368e34882271a92b0717c9c8f Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMzE5OTg3Y2MwZTg3ODlhMzY4ZTM0ODgyMjcxYTkyYjA3MTdjOWM4ZiJ9 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/.flake8 | 33 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 ++ .../functions_v1/cloud_functions_service.rst | 10 + .../v1/docs/functions_v1/services.rst | 6 + .../v1/docs/functions_v1/types.rst | 7 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/google/cloud/functions/__init__.py | 67 + .../v1/google/cloud/functions/py.typed | 2 + .../v1/google/cloud/functions_v1/__init__.py | 68 + .../cloud/functions_v1/gapic_metadata.json | 133 + .../v1/google/cloud/functions_v1/py.typed | 2 + .../cloud/functions_v1/services/__init__.py | 15 + .../cloud_functions_service/__init__.py | 22 + .../cloud_functions_service/async_client.py | 1423 ++++++ .../cloud_functions_service/client.py | 1613 +++++++ .../cloud_functions_service/pagers.py | 139 + .../transports/__init__.py | 33 + .../transports/base.py | 331 ++ .../transports/grpc.py | 593 +++ .../transports/grpc_asyncio.py | 592 +++ .../cloud/functions_v1/types/__init__.py | 66 + .../cloud/functions_v1/types/functions.py | 1067 +++++ .../cloud/functions_v1/types/operations.py | 108 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 180 + ...d_functions_service_call_function_async.py | 46 + ...ud_functions_service_call_function_sync.py | 46 + ...functions_service_create_function_async.py | 53 + ..._functions_service_create_function_sync.py | 53 + ...functions_service_delete_function_async.py | 49 + ..._functions_service_delete_function_sync.py | 49 + ...ons_service_generate_download_url_async.py | 44 + ...ions_service_generate_download_url_sync.py | 44 + ...tions_service_generate_upload_url_async.py | 44 + ...ctions_service_generate_upload_url_sync.py | 44 + ...ud_functions_service_get_function_async.py | 45 + ...oud_functions_service_get_function_sync.py | 45 + ..._functions_service_get_iam_policy_async.py | 46 + ...d_functions_service_get_iam_policy_sync.py | 46 + ..._functions_service_list_functions_async.py | 45 + ...d_functions_service_list_functions_sync.py | 45 + ..._functions_service_set_iam_policy_async.py | 46 + ...d_functions_service_set_iam_policy_sync.py | 46 + ...ions_service_test_iam_permissions_async.py | 47 + ...tions_service_test_iam_permissions_sync.py | 47 + ...functions_service_update_function_async.py | 52 + ..._functions_service_update_function_sync.py | 52 + .../snippet_metadata_functions_v1.json | 1753 +++++++ .../v1/scripts/fixup_functions_v1_keywords.py | 186 + owl-bot-staging/v1/setup.py | 60 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/functions_v1/__init__.py | 16 + .../test_cloud_functions_service.py | 3681 +++++++++++++++ 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 ++ .../v2/docs/functions_v2/function_service.rst | 10 + .../v2/docs/functions_v2/services.rst | 6 + .../v2/docs/functions_v2/types.rst | 7 + owl-bot-staging/v2/docs/index.rst | 7 + .../v2/google/cloud/functions/__init__.py | 77 + .../v2/google/cloud/functions/py.typed | 2 + .../v2/google/cloud/functions_v2/__init__.py | 78 + .../cloud/functions_v2/gapic_metadata.json | 103 + .../v2/google/cloud/functions_v2/py.typed | 2 + .../cloud/functions_v2/services/__init__.py | 15 + .../services/function_service/__init__.py | 22 + .../services/function_service/async_client.py | 1518 ++++++ .../services/function_service/client.py | 1787 +++++++ .../services/function_service/pagers.py | 139 + .../function_service/transports/__init__.py | 33 + .../function_service/transports/base.py | 319 ++ .../function_service/transports/grpc.py | 645 +++ .../transports/grpc_asyncio.py | 644 +++ .../cloud/functions_v2/types/__init__.py | 74 + .../cloud/functions_v2/types/functions.py | 1363 ++++++ owl-bot-staging/v2/mypy.ini | 3 + owl-bot-staging/v2/noxfile.py | 180 + ..._function_service_create_function_async.py | 49 + ...d_function_service_create_function_sync.py | 49 + ..._function_service_delete_function_async.py | 49 + ...d_function_service_delete_function_sync.py | 49 + ...ion_service_generate_download_url_async.py | 45 + ...tion_service_generate_download_url_sync.py | 45 + ...ction_service_generate_upload_url_async.py | 45 + ...nction_service_generate_upload_url_sync.py | 45 + ...ted_function_service_get_function_async.py | 45 + ...ated_function_service_get_function_sync.py | 45 + ...d_function_service_list_functions_async.py | 46 + ...ed_function_service_list_functions_sync.py | 46 + ...ed_function_service_list_runtimes_async.py | 45 + ...ted_function_service_list_runtimes_sync.py | 45 + ..._function_service_update_function_async.py | 48 + ...d_function_service_update_function_sync.py | 48 + .../snippet_metadata_functions_v2.json | 1310 ++++++ .../v2/scripts/fixup_functions_v2_keywords.py | 183 + 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 + .../tests/unit/gapic/functions_v2/__init__.py | 16 + .../functions_v2/test_function_service.py | 4158 +++++++++++++++++ 109 files changed, 27772 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/.flake8 create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst create mode 100644 owl-bot-staging/v1/docs/functions_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/functions_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/cloud/functions/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py create mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json create mode 100644 owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py 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/functions_v2/function_service.rst create mode 100644 owl-bot-staging/v2/docs/functions_v2/services.rst create mode 100644 owl-bot-staging/v2/docs/functions_v2/types.rst create mode 100644 owl-bot-staging/v2/docs/index.rst create mode 100644 owl-bot-staging/v2/google/cloud/functions/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/functions/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/gapic_metadata.json create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/services/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/client.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/types/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/types/functions.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/cloudfunctions_v2_generated_function_service_create_function_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_functions_v2.json create mode 100644 owl-bot-staging/v2/scripts/fixup_functions_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/functions_v2/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/functions_v2/test_function_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..ca93bdf --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/functions/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 0000000..9e8399a --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/functions *.py +recursive-include google/cloud/functions_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..533650a --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Functions 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 Functions API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..3464a12 --- /dev/null +++ b/owl-bot-staging/v1/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-functions 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-functions" +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-functions-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-functions.tex", + u"google-cloud-functions 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-functions", + u"Google Cloud Functions 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-functions", + u"google-cloud-functions Documentation", + author, + "google-cloud-functions", + "GAPIC library for Google Cloud Functions API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst b/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst new file mode 100644 index 0000000..36d0114 --- /dev/null +++ b/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst @@ -0,0 +1,10 @@ +CloudFunctionsService +--------------------------------------- + +.. automodule:: google.cloud.functions_v1.services.cloud_functions_service + :members: + :inherited-members: + +.. automodule:: google.cloud.functions_v1.services.cloud_functions_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/functions_v1/services.rst b/owl-bot-staging/v1/docs/functions_v1/services.rst new file mode 100644 index 0000000..89ae970 --- /dev/null +++ b/owl-bot-staging/v1/docs/functions_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Functions v1 API +========================================== +.. toctree:: + :maxdepth: 2 + + cloud_functions_service diff --git a/owl-bot-staging/v1/docs/functions_v1/types.rst b/owl-bot-staging/v1/docs/functions_v1/types.rst new file mode 100644 index 0000000..bebdfe9 --- /dev/null +++ b/owl-bot-staging/v1/docs/functions_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Functions v1 API +======================================= + +.. automodule:: google.cloud.functions_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..dc30f6d --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + functions_v1/services + functions_v1/types diff --git a/owl-bot-staging/v1/google/cloud/functions/__init__.py b/owl-bot-staging/v1/google/cloud/functions/__init__.py new file mode 100644 index 0000000..c34f3b0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions/__init__.py @@ -0,0 +1,67 @@ +# -*- 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.functions_v1.services.cloud_functions_service.client import CloudFunctionsServiceClient +from google.cloud.functions_v1.services.cloud_functions_service.async_client import CloudFunctionsServiceAsyncClient + +from google.cloud.functions_v1.types.functions import CallFunctionRequest +from google.cloud.functions_v1.types.functions import CallFunctionResponse +from google.cloud.functions_v1.types.functions import CloudFunction +from google.cloud.functions_v1.types.functions import CreateFunctionRequest +from google.cloud.functions_v1.types.functions import DeleteFunctionRequest +from google.cloud.functions_v1.types.functions import EventTrigger +from google.cloud.functions_v1.types.functions import FailurePolicy +from google.cloud.functions_v1.types.functions import GenerateDownloadUrlRequest +from google.cloud.functions_v1.types.functions import GenerateDownloadUrlResponse +from google.cloud.functions_v1.types.functions import GenerateUploadUrlRequest +from google.cloud.functions_v1.types.functions import GenerateUploadUrlResponse +from google.cloud.functions_v1.types.functions import GetFunctionRequest +from google.cloud.functions_v1.types.functions import HttpsTrigger +from google.cloud.functions_v1.types.functions import ListFunctionsRequest +from google.cloud.functions_v1.types.functions import ListFunctionsResponse +from google.cloud.functions_v1.types.functions import SecretEnvVar +from google.cloud.functions_v1.types.functions import SecretVolume +from google.cloud.functions_v1.types.functions import SourceRepository +from google.cloud.functions_v1.types.functions import UpdateFunctionRequest +from google.cloud.functions_v1.types.functions import CloudFunctionStatus +from google.cloud.functions_v1.types.operations import OperationMetadataV1 +from google.cloud.functions_v1.types.operations import OperationType + +__all__ = ('CloudFunctionsServiceClient', + 'CloudFunctionsServiceAsyncClient', + 'CallFunctionRequest', + 'CallFunctionResponse', + 'CloudFunction', + 'CreateFunctionRequest', + 'DeleteFunctionRequest', + 'EventTrigger', + 'FailurePolicy', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GetFunctionRequest', + 'HttpsTrigger', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'SecretEnvVar', + 'SecretVolume', + 'SourceRepository', + 'UpdateFunctionRequest', + 'CloudFunctionStatus', + 'OperationMetadataV1', + 'OperationType', +) diff --git a/owl-bot-staging/v1/google/cloud/functions/py.typed b/owl-bot-staging/v1/google/cloud/functions/py.typed new file mode 100644 index 0000000..982ebb1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py new file mode 100644 index 0000000..87351c6 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py @@ -0,0 +1,68 @@ +# -*- 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.cloud_functions_service import CloudFunctionsServiceClient +from .services.cloud_functions_service import CloudFunctionsServiceAsyncClient + +from .types.functions import CallFunctionRequest +from .types.functions import CallFunctionResponse +from .types.functions import CloudFunction +from .types.functions import CreateFunctionRequest +from .types.functions import DeleteFunctionRequest +from .types.functions import EventTrigger +from .types.functions import FailurePolicy +from .types.functions import GenerateDownloadUrlRequest +from .types.functions import GenerateDownloadUrlResponse +from .types.functions import GenerateUploadUrlRequest +from .types.functions import GenerateUploadUrlResponse +from .types.functions import GetFunctionRequest +from .types.functions import HttpsTrigger +from .types.functions import ListFunctionsRequest +from .types.functions import ListFunctionsResponse +from .types.functions import SecretEnvVar +from .types.functions import SecretVolume +from .types.functions import SourceRepository +from .types.functions import UpdateFunctionRequest +from .types.functions import CloudFunctionStatus +from .types.operations import OperationMetadataV1 +from .types.operations import OperationType + +__all__ = ( + 'CloudFunctionsServiceAsyncClient', +'CallFunctionRequest', +'CallFunctionResponse', +'CloudFunction', +'CloudFunctionStatus', +'CloudFunctionsServiceClient', +'CreateFunctionRequest', +'DeleteFunctionRequest', +'EventTrigger', +'FailurePolicy', +'GenerateDownloadUrlRequest', +'GenerateDownloadUrlResponse', +'GenerateUploadUrlRequest', +'GenerateUploadUrlResponse', +'GetFunctionRequest', +'HttpsTrigger', +'ListFunctionsRequest', +'ListFunctionsResponse', +'OperationMetadataV1', +'OperationType', +'SecretEnvVar', +'SecretVolume', +'SourceRepository', +'UpdateFunctionRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json new file mode 100644 index 0000000..5745d05 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json @@ -0,0 +1,133 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.functions_v1", + "protoPackage": "google.cloud.functions.v1", + "schema": "1.0", + "services": { + "CloudFunctionsService": { + "clients": { + "grpc": { + "libraryClient": "CloudFunctionsServiceClient", + "rpcs": { + "CallFunction": { + "methods": [ + "call_function" + ] + }, + "CreateFunction": { + "methods": [ + "create_function" + ] + }, + "DeleteFunction": { + "methods": [ + "delete_function" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "generate_download_url" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "generate_upload_url" + ] + }, + "GetFunction": { + "methods": [ + "get_function" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListFunctions": { + "methods": [ + "list_functions" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFunction": { + "methods": [ + "update_function" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudFunctionsServiceAsyncClient", + "rpcs": { + "CallFunction": { + "methods": [ + "call_function" + ] + }, + "CreateFunction": { + "methods": [ + "create_function" + ] + }, + "DeleteFunction": { + "methods": [ + "delete_function" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "generate_download_url" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "generate_upload_url" + ] + }, + "GetFunction": { + "methods": [ + "get_function" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListFunctions": { + "methods": [ + "list_functions" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFunction": { + "methods": [ + "update_function" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/py.typed b/owl-bot-staging/v1/google/cloud/functions_v1/py.typed new file mode 100644 index 0000000..982ebb1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/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/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py new file mode 100644 index 0000000..d784dc7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__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 CloudFunctionsServiceClient +from .async_client import CloudFunctionsServiceAsyncClient + +__all__ = ( + 'CloudFunctionsServiceClient', + 'CloudFunctionsServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py new file mode 100644 index 0000000..3010041 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py @@ -0,0 +1,1423 @@ +# -*- 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_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.functions_v1.services.cloud_functions_service import pagers +from google.cloud.functions_v1.types import functions +from google.cloud.functions_v1.types import operations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport +from .client import CloudFunctionsServiceClient + + +class CloudFunctionsServiceAsyncClient: + """A service that application uses to manipulate triggers and + functions. + """ + + _client: CloudFunctionsServiceClient + + DEFAULT_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT + + cloud_function_path = staticmethod(CloudFunctionsServiceClient.cloud_function_path) + parse_cloud_function_path = staticmethod(CloudFunctionsServiceClient.parse_cloud_function_path) + crypto_key_path = staticmethod(CloudFunctionsServiceClient.crypto_key_path) + parse_crypto_key_path = staticmethod(CloudFunctionsServiceClient.parse_crypto_key_path) + repository_path = staticmethod(CloudFunctionsServiceClient.repository_path) + parse_repository_path = staticmethod(CloudFunctionsServiceClient.parse_repository_path) + common_billing_account_path = staticmethod(CloudFunctionsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CloudFunctionsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CloudFunctionsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CloudFunctionsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CloudFunctionsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CloudFunctionsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CloudFunctionsServiceClient.common_project_path) + parse_common_project_path = staticmethod(CloudFunctionsServiceClient.parse_common_project_path) + common_location_path = staticmethod(CloudFunctionsServiceClient.common_location_path) + parse_common_location_path = staticmethod(CloudFunctionsServiceClient.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: + CloudFunctionsServiceAsyncClient: The constructed client. + """ + return CloudFunctionsServiceClient.from_service_account_info.__func__(CloudFunctionsServiceAsyncClient, 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: + CloudFunctionsServiceAsyncClient: The constructed client. + """ + return CloudFunctionsServiceClient.from_service_account_file.__func__(CloudFunctionsServiceAsyncClient, 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 CloudFunctionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CloudFunctionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CloudFunctionsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CloudFunctionsServiceClient).get_transport_class, type(CloudFunctionsServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CloudFunctionsServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud functions service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CloudFunctionsServiceTransport]): 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 = CloudFunctionsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_functions(self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsAsyncPager: + r"""Returns a list of functions that belong to the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): + The request object. Request for the `ListFunctions` + 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager: + Response for the ListFunctions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = functions.ListFunctionsRequest(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.list_functions, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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.ListFunctionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_function(self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CloudFunction: + r"""Returns a function with the given name from the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): + The request object. Request for the `GetFunction` + method. + name (:class:`str`): + Required. The name of the function + which details should be obtained. + + 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.functions_v1.types.CloudFunction: + Describes a Cloud Function that + contains user computation executed in + response to an event. It encapsulate + function and triggers configurations. + + """ + # 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 = functions.GetFunctionRequest(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_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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 create_function(self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + location: str = None, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): + The request object. Request for the `CreateFunction` + method. + location (:class:`str`): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``location`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function (:class:`google.cloud.functions_v1.types.CloudFunction`): + Required. Function to be created. + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([location, function]) + if request is 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 = functions.CreateFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if location is not None: + request.location = location + if function is not None: + request.function = function + + # 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_function, + default_timeout=600.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(( + ("location", request.location), + )), + ) + + # 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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def update_function(self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates existing function. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): + The request object. Request for the `UpdateFunction` + method. + function (:class:`google.cloud.functions_v1.types.CloudFunction`): + Required. New version of the + function. + + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([function]) + if request is 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 = functions.UpdateFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if function is not None: + request.function = function + + # 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_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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(( + ("function.name", request.function.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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def delete_function(self, + request: Union[functions.DeleteFunctionRequest, 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 function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): + The request object. Request for the `DeleteFunction` + method. + name (:class:`str`): + Required. The name of the function + which should be deleted. + + 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.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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 = functions.DeleteFunctionRequest(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_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.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, + empty_pb2.Empty, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def call_function(self, + request: Union[functions.CallFunctionRequest, dict] = None, + *, + name: str = None, + data: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CallFunctionResponse: + r"""Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = await client.call_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): + The request object. Request for the `CallFunction` + method. + name (:class:`str`): + Required. The name of the function to + be called. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (:class:`str`): + Required. Input to be passed to the + function. + + This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: + Response of CallFunction method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, data]) + if request is 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 = functions.CallFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.call_function, + default_timeout=600.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 generate_upload_url(self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: + r"""Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = await client.generate_upload_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): + The request object. Request of `GenerateSourceUploadUrl` + 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.cloud.functions_v1.types.GenerateUploadUrlResponse: + Response of GenerateSourceUploadUrl method. + """ + # Create or coerce a protobuf request object. + request = functions.GenerateUploadUrlRequest(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.generate_upload_url, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_download_url(self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: + r"""Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + .. code-block:: python + + from google.cloud import functions_v1 + + async def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = await client.generate_download_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): + The request object. Request of `GenerateDownloadUrl` + 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: + Response of GenerateDownloadUrl method. + """ + # Create or coerce a protobuf request object. + request = functions.GenerateDownloadUrlRequest(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.generate_download_url, + 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 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 on the specified + function. Replaces any existing policy. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await 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 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"""Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await 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 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"""Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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) + + 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-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CloudFunctionsServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py new file mode 100644 index 0000000..53c6f1a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py @@ -0,0 +1,1613 @@ +# -*- 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_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.functions_v1.services.cloud_functions_service import pagers +from google.cloud.functions_v1.types import functions +from google.cloud.functions_v1.types import operations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CloudFunctionsServiceGrpcTransport +from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport + + +class CloudFunctionsServiceClientMeta(type): + """Metaclass for the CloudFunctionsService 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[CloudFunctionsServiceTransport]] + _transport_registry["grpc"] = CloudFunctionsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CloudFunctionsServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CloudFunctionsServiceTransport]: + """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 CloudFunctionsServiceClient(metaclass=CloudFunctionsServiceClientMeta): + """A service that application uses to manipulate triggers and + functions. + """ + + @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 = "cloudfunctions.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: + CloudFunctionsServiceClient: 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: + CloudFunctionsServiceClient: 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) -> CloudFunctionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CloudFunctionsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def cloud_function_path(project: str,location: str,function: str,) -> str: + """Returns a fully-qualified cloud_function string.""" + return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + + @staticmethod + def parse_cloud_function_path(path: str) -> Dict[str,str]: + """Parses a cloud_function path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?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 repository_path(project: str,location: str,repository: str,) -> str: + """Returns a fully-qualified repository string.""" + return "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) + + @staticmethod + def parse_repository_path(path: str) -> Dict[str,str]: + """Parses a repository path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/repositories/(?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, CloudFunctionsServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud functions service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CloudFunctionsServiceTransport]): 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, CloudFunctionsServiceTransport): + # transport is a CloudFunctionsServiceTransport 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, + api_audience=client_options.api_audience, + ) + + def list_functions(self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsPager: + r"""Returns a list of functions that belong to the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): + The request object. Request for the `ListFunctions` + 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager: + Response for the ListFunctions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.ListFunctionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.ListFunctionsRequest): + request = functions.ListFunctionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_functions] + + # 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.ListFunctionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_function(self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CloudFunction: + r"""Returns a function with the given name from the + requested project. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = client.get_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): + The request object. Request for the `GetFunction` + method. + name (str): + Required. The name of the function + which details should be obtained. + + 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.functions_v1.types.CloudFunction: + Describes a Cloud Function that + contains user computation executed in + response to an event. It encapsulate + function and triggers configurations. + + """ + # 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 functions.GetFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GetFunctionRequest): + request = functions.GetFunctionRequest(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_function] + + # 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 create_function(self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + location: str = None, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): + The request object. Request for the `CreateFunction` + method. + location (str): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``location`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function (google.cloud.functions_v1.types.CloudFunction): + Required. Function to be created. + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([location, function]) + if request is 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 functions.CreateFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.CreateFunctionRequest): + request = functions.CreateFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if location is not None: + request.location = location + if function is not None: + request.function = function + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("location", request.location), + )), + ) + + # 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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def update_function(self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.CloudFunction = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates existing function. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): + The request object. Request for the `UpdateFunction` + method. + function (google.cloud.functions_v1.types.CloudFunction): + Required. New version of the + function. + + This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulate function and + triggers configurations. + + """ + # 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([function]) + if request is 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 functions.UpdateFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.UpdateFunctionRequest): + request = functions.UpdateFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if function is not None: + request.function = function + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("function.name", request.function.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, + functions.CloudFunction, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def delete_function(self, + request: Union[functions.DeleteFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): + The request object. Request for the `DeleteFunction` + method. + name (str): + Required. The name of the function + which should be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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 functions.DeleteFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.DeleteFunctionRequest): + request = functions.DeleteFunctionRequest(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_function] + + # 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, + empty_pb2.Empty, + metadata_type=operations.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def call_function(self, + request: Union[functions.CallFunctionRequest, dict] = None, + *, + name: str = None, + data: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.CallFunctionResponse: + r"""Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = client.call_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): + The request object. Request for the `CallFunction` + method. + name (str): + Required. The name of the function to + be called. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (str): + Required. Input to be passed to the + function. + + This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: + Response of CallFunction method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, data]) + if request is 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 functions.CallFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.CallFunctionRequest): + request = functions.CallFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.call_function] + + # 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 generate_upload_url(self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: + r"""Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = client.generate_upload_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): + The request object. Request of `GenerateSourceUploadUrl` + 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.cloud.functions_v1.types.GenerateUploadUrlResponse: + Response of GenerateSourceUploadUrl method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.GenerateUploadUrlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GenerateUploadUrlRequest): + request = functions.GenerateUploadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_upload_url] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_download_url(self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: + r"""Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + .. code-block:: python + + from google.cloud import functions_v1 + + def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = client.generate_download_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): + The request object. Request of `GenerateDownloadUrl` + 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: + Response of GenerateDownloadUrl method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.GenerateDownloadUrlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GenerateDownloadUrlRequest): + request = functions.GenerateDownloadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_download_url] + + # 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 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 on the specified + function. Replaces any existing policy. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 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"""Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 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"""Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + .. code-block:: python + + from google.cloud import functions_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CloudFunctionsServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py new file mode 100644 index 0000000..f31d4f1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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.functions_v1.types import functions + + +class ListFunctionsPager: + """A pager for iterating through ``list_functions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``functions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFunctions`` requests and continue to iterate + through the ``functions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` + 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[..., functions.ListFunctionsResponse], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + 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.functions_v1.types.ListFunctionsRequest): + The initial request object. + response (google.cloud.functions_v1.types.ListFunctionsResponse): + 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 = functions.ListFunctionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[functions.ListFunctionsResponse]: + 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[functions.CloudFunction]: + for page in self.pages: + yield from page.functions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFunctionsAsyncPager: + """A pager for iterating through ``list_functions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``functions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFunctions`` requests and continue to iterate + through the ``functions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` + 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[functions.ListFunctionsResponse]], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + 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.functions_v1.types.ListFunctionsRequest): + The initial request object. + response (google.cloud.functions_v1.types.ListFunctionsResponse): + 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 = functions.ListFunctionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[functions.ListFunctionsResponse]: + 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[functions.CloudFunction]: + async def async_generator(): + async for page in self.pages: + for response in page.functions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py new file mode 100644 index 0000000..ac1ba7e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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 CloudFunctionsServiceTransport +from .grpc import CloudFunctionsServiceGrpcTransport +from .grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CloudFunctionsServiceTransport]] +_transport_registry['grpc'] = CloudFunctionsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CloudFunctionsServiceGrpcAsyncIOTransport + +__all__ = ( + 'CloudFunctionsServiceTransport', + 'CloudFunctionsServiceGrpcTransport', + 'CloudFunctionsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py new file mode 100644 index 0000000..2d3352f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py @@ -0,0 +1,331 @@ +# -*- 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.functions_v1.types import functions +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-functions', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CloudFunctionsServiceTransport(abc.ABC): + """Abstract transport class for CloudFunctionsService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'cloudfunctions.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, + api_audience: Optional[str] = None, + **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. + """ + + 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) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_functions: gapic_v1.method.wrap_method( + self.list_functions, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_function: gapic_v1.method.wrap_method( + self.get_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.create_function: gapic_v1.method.wrap_method( + self.create_function, + default_timeout=600.0, + client_info=client_info, + ), + self.update_function: gapic_v1.method.wrap_method( + self.update_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_function: gapic_v1.method.wrap_method( + self.delete_function, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.call_function: gapic_v1.method.wrap_method( + self.call_function, + default_timeout=600.0, + client_info=client_info, + ), + self.generate_upload_url: gapic_v1.method.wrap_method( + self.generate_upload_url, + default_timeout=None, + client_info=client_info, + ), + self.generate_download_url: gapic_v1.method.wrap_method( + self.generate_download_url, + 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.get_iam_policy: gapic_v1.method.wrap_method( + self.get_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 list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + Union[ + functions.ListFunctionsResponse, + Awaitable[functions.ListFunctionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_function(self) -> Callable[ + [functions.GetFunctionRequest], + Union[ + functions.CloudFunction, + Awaitable[functions.CloudFunction] + ]]: + raise NotImplementedError() + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def call_function(self) -> Callable[ + [functions.CallFunctionRequest], + Union[ + functions.CallFunctionResponse, + Awaitable[functions.CallFunctionResponse] + ]]: + raise NotImplementedError() + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + Union[ + functions.GenerateUploadUrlResponse, + Awaitable[functions.GenerateUploadUrlResponse] + ]]: + raise NotImplementedError() + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Union[ + functions.GenerateDownloadUrlResponse, + Awaitable[functions.GenerateDownloadUrlResponse] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CloudFunctionsServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py new file mode 100644 index 0000000..92c02c9 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py @@ -0,0 +1,593 @@ +# -*- 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.functions_v1.types import functions +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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO + + +class CloudFunctionsServiceGrpcTransport(CloudFunctionsServiceTransport): + """gRPC backend transport for CloudFunctionsService. + + A service that application uses to manipulate triggers and + functions. + + 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 = 'cloudfunctions.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, + api_audience: Optional[str] = None, + ) -> 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, + api_audience=api_audience, + ) + + 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 = 'cloudfunctions.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 list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + functions.ListFunctionsResponse]: + r"""Return a callable for the list functions method over gRPC. + + Returns a list of functions that belong to the + requested project. + + Returns: + Callable[[~.ListFunctionsRequest], + ~.ListFunctionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_functions' not in self._stubs: + self._stubs['list_functions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', + request_serializer=functions.ListFunctionsRequest.serialize, + response_deserializer=functions.ListFunctionsResponse.deserialize, + ) + return self._stubs['list_functions'] + + @property + def get_function(self) -> Callable[ + [functions.GetFunctionRequest], + functions.CloudFunction]: + r"""Return a callable for the get function method over gRPC. + + Returns a function with the given name from the + requested project. + + Returns: + Callable[[~.GetFunctionRequest], + ~.CloudFunction]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_function' not in self._stubs: + self._stubs['get_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', + request_serializer=functions.GetFunctionRequest.serialize, + response_deserializer=functions.CloudFunction.deserialize, + ) + return self._stubs['get_function'] + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create function method over gRPC. + + Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + Returns: + Callable[[~.CreateFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['create_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', + request_serializer=functions.CreateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_function'] + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the update function method over gRPC. + + Updates existing function. + + Returns: + Callable[[~.UpdateFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['update_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', + request_serializer=functions.UpdateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_function'] + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete function method over gRPC. + + Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + Returns: + Callable[[~.DeleteFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['delete_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', + request_serializer=functions.DeleteFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_function'] + + @property + def call_function(self) -> Callable[ + [functions.CallFunctionRequest], + functions.CallFunctionResponse]: + r"""Return a callable for the call function method over gRPC. + + Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + Returns: + Callable[[~.CallFunctionRequest], + ~.CallFunctionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'call_function' not in self._stubs: + self._stubs['call_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', + request_serializer=functions.CallFunctionRequest.serialize, + response_deserializer=functions.CallFunctionResponse.deserialize, + ) + return self._stubs['call_function'] + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + functions.GenerateUploadUrlResponse]: + r"""Return a callable for the generate upload url method over gRPC. + + Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + Returns: + Callable[[~.GenerateUploadUrlRequest], + ~.GenerateUploadUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_upload_url' not in self._stubs: + self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', + request_serializer=functions.GenerateUploadUrlRequest.serialize, + response_deserializer=functions.GenerateUploadUrlResponse.deserialize, + ) + return self._stubs['generate_upload_url'] + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + functions.GenerateDownloadUrlResponse]: + r"""Return a callable for the generate download url method over gRPC. + + Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + Returns: + Callable[[~.GenerateDownloadUrlRequest], + ~.GenerateDownloadUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_download_url' not in self._stubs: + self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', + request_serializer=functions.GenerateDownloadUrlRequest.serialize, + response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, + ) + return self._stubs['generate_download_url'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/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__ = ( + 'CloudFunctionsServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..d05047d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py @@ -0,0 +1,592 @@ +# -*- 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.functions_v1.types import functions +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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CloudFunctionsServiceGrpcTransport + + +class CloudFunctionsServiceGrpcAsyncIOTransport(CloudFunctionsServiceTransport): + """gRPC AsyncIO backend transport for CloudFunctionsService. + + A service that application uses to manipulate triggers and + functions. + + 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 = 'cloudfunctions.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 = 'cloudfunctions.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, + api_audience: Optional[str] = None, + ) -> 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, + api_audience=api_audience, + ) + + 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 list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + Awaitable[functions.ListFunctionsResponse]]: + r"""Return a callable for the list functions method over gRPC. + + Returns a list of functions that belong to the + requested project. + + Returns: + Callable[[~.ListFunctionsRequest], + Awaitable[~.ListFunctionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_functions' not in self._stubs: + self._stubs['list_functions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', + request_serializer=functions.ListFunctionsRequest.serialize, + response_deserializer=functions.ListFunctionsResponse.deserialize, + ) + return self._stubs['list_functions'] + + @property + def get_function(self) -> Callable[ + [functions.GetFunctionRequest], + Awaitable[functions.CloudFunction]]: + r"""Return a callable for the get function method over gRPC. + + Returns a function with the given name from the + requested project. + + Returns: + Callable[[~.GetFunctionRequest], + Awaitable[~.CloudFunction]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_function' not in self._stubs: + self._stubs['get_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', + request_serializer=functions.GetFunctionRequest.serialize, + response_deserializer=functions.CloudFunction.deserialize, + ) + return self._stubs['get_function'] + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create function method over gRPC. + + Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + Returns: + Callable[[~.CreateFunctionRequest], + 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_function' not in self._stubs: + self._stubs['create_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', + request_serializer=functions.CreateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_function'] + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update function method over gRPC. + + Updates existing function. + + Returns: + Callable[[~.UpdateFunctionRequest], + 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_function' not in self._stubs: + self._stubs['update_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', + request_serializer=functions.UpdateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_function'] + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete function method over gRPC. + + Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + Returns: + Callable[[~.DeleteFunctionRequest], + 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_function' not in self._stubs: + self._stubs['delete_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', + request_serializer=functions.DeleteFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_function'] + + @property + def call_function(self) -> Callable[ + [functions.CallFunctionRequest], + Awaitable[functions.CallFunctionResponse]]: + r"""Return a callable for the call function method over gRPC. + + Synchronously invokes a deployed Cloud Function. To be used for + testing purposes as very limited traffic is allowed. For more + information on the actual limits, refer to `Rate + Limits `__. + + Returns: + Callable[[~.CallFunctionRequest], + Awaitable[~.CallFunctionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'call_function' not in self._stubs: + self._stubs['call_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', + request_serializer=functions.CallFunctionRequest.serialize, + response_deserializer=functions.CallFunctionResponse.deserialize, + ) + return self._stubs['call_function'] + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + Awaitable[functions.GenerateUploadUrlResponse]]: + r"""Return a callable for the generate upload url method over gRPC. + + Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - Source file size should not exceed 100MB limit. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + - ``x-goog-content-length-range: 0,104857600`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + Returns: + Callable[[~.GenerateUploadUrlRequest], + Awaitable[~.GenerateUploadUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_upload_url' not in self._stubs: + self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', + request_serializer=functions.GenerateUploadUrlRequest.serialize, + response_deserializer=functions.GenerateUploadUrlResponse.deserialize, + ) + return self._stubs['generate_upload_url'] + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Awaitable[functions.GenerateDownloadUrlResponse]]: + r"""Return a callable for the generate download url method over gRPC. + + Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within minutes after + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + Returns: + Callable[[~.GenerateDownloadUrlRequest], + Awaitable[~.GenerateDownloadUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_download_url' not in self._stubs: + self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', + request_serializer=functions.GenerateDownloadUrlRequest.serialize, + response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, + ) + return self._stubs['generate_download_url'] + + @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 on the specified + function. Replaces 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.functions.v1.CloudFunctionsService/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + 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.functions.v1.CloudFunctionsService/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Returns: + Callable[[~.TestIamPermissionsRequest], + 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.functions.v1.CloudFunctionsService/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__ = ( + 'CloudFunctionsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py new file mode 100644 index 0000000..b09e206 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py @@ -0,0 +1,66 @@ +# -*- 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 .functions import ( + CallFunctionRequest, + CallFunctionResponse, + CloudFunction, + CreateFunctionRequest, + DeleteFunctionRequest, + EventTrigger, + FailurePolicy, + GenerateDownloadUrlRequest, + GenerateDownloadUrlResponse, + GenerateUploadUrlRequest, + GenerateUploadUrlResponse, + GetFunctionRequest, + HttpsTrigger, + ListFunctionsRequest, + ListFunctionsResponse, + SecretEnvVar, + SecretVolume, + SourceRepository, + UpdateFunctionRequest, + CloudFunctionStatus, +) +from .operations import ( + OperationMetadataV1, + OperationType, +) + +__all__ = ( + 'CallFunctionRequest', + 'CallFunctionResponse', + 'CloudFunction', + 'CreateFunctionRequest', + 'DeleteFunctionRequest', + 'EventTrigger', + 'FailurePolicy', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GetFunctionRequest', + 'HttpsTrigger', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'SecretEnvVar', + 'SecretVolume', + 'SourceRepository', + 'UpdateFunctionRequest', + 'CloudFunctionStatus', + 'OperationMetadataV1', + 'OperationType', +) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py new file mode 100644 index 0000000..844c961 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py @@ -0,0 +1,1067 @@ +# -*- 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 duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.functions.v1', + manifest={ + 'CloudFunctionStatus', + 'CloudFunction', + 'SourceRepository', + 'HttpsTrigger', + 'EventTrigger', + 'FailurePolicy', + 'SecretEnvVar', + 'SecretVolume', + 'CreateFunctionRequest', + 'UpdateFunctionRequest', + 'GetFunctionRequest', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'DeleteFunctionRequest', + 'CallFunctionRequest', + 'CallFunctionResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + }, +) + + +class CloudFunctionStatus(proto.Enum): + r"""Describes the current stage of a deployment.""" + CLOUD_FUNCTION_STATUS_UNSPECIFIED = 0 + ACTIVE = 1 + OFFLINE = 2 + DEPLOY_IN_PROGRESS = 3 + DELETE_IN_PROGRESS = 4 + UNKNOWN = 5 + + +class CloudFunction(proto.Message): + r"""Describes a Cloud Function that contains user computation + executed in response to an event. It encapsulate function and + triggers configurations. + + 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): + A user-defined name of the function. Function names must be + unique globally and match pattern + ``projects/*/locations/*/functions/*`` + description (str): + User-provided description of a function. + source_archive_url (str): + The Google Cloud Storage URL, starting with ``gs://``, + pointing to the zip archive which contains the function. + + This field is a member of `oneof`_ ``source_code``. + source_repository (google.cloud.functions_v1.types.SourceRepository): + **Beta Feature** + + The source repository where a function is hosted. + + This field is a member of `oneof`_ ``source_code``. + source_upload_url (str): + The Google Cloud Storage signed URL used for source + uploading, generated by calling + [google.cloud.functions.v1.GenerateUploadUrl]. + + The signature is validated on write methods (Create, Update) + The signature is stripped from the Function object on read + methods (Get, List) + + This field is a member of `oneof`_ ``source_code``. + https_trigger (google.cloud.functions_v1.types.HttpsTrigger): + An HTTPS endpoint type of source that can be + triggered via URL. + + This field is a member of `oneof`_ ``trigger``. + event_trigger (google.cloud.functions_v1.types.EventTrigger): + A source that fires events in response to a + condition in another service. + + This field is a member of `oneof`_ ``trigger``. + status (google.cloud.functions_v1.types.CloudFunctionStatus): + Output only. Status of the function + deployment. + entry_point (str): + The name of the function (as defined in source code) that + will be executed. Defaults to the resource name suffix, if + not specified. For backward compatibility, if function with + given name is not found, then the system will try to use + function named "function". For Node.js this is name of a + function exported by the module specified in + ``source_location``. + runtime (str): + The runtime in which to run the function. Required when + deploying a new function, optional when updating an existing + function. For a complete list of possible choices, see the + ```gcloud`` command + reference `__. + timeout (google.protobuf.duration_pb2.Duration): + The function execution timeout. Execution is + considered failed and can be terminated if the + function is not completed at the end of the + timeout period. Defaults to 60 seconds. + available_memory_mb (int): + The amount of memory in MB available for a + function. Defaults to 256MB. + service_account_email (str): + The email of the function's service account. If empty, + defaults to ``{project_id}@appspot.gserviceaccount.com``. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update timestamp of a + Cloud Function. + version_id (int): + Output only. The version identifier of the + Cloud Function. Each deployment attempt results + in a new version of a function being created. + labels (Mapping[str, str]): + Labels associated with this Cloud Function. + environment_variables (Mapping[str, str]): + Environment variables that shall be available + during function execution. + build_environment_variables (Mapping[str, str]): + Build environment variables that shall be + available during build time. + network (str): + The VPC Network that this cloud function can connect to. It + can be either the fully-qualified URI, or the short name of + the network resource. If the short network name is used, the + network must belong to the same project. Otherwise, it must + belong to a project within the same organization. The format + of this field is either + ``projects/{project}/global/networks/{network}`` or + ``{network}``, where ``{project}`` is a project id where the + network is defined, and ``{network}`` is the short name of + the network. + + This field is mutually exclusive with ``vpc_connector`` and + will be replaced by it. + + See `the VPC + documentation `__ + for more information on connecting Cloud projects. + max_instances (int): + The limit on the maximum number of function instances that + may coexist at a given time. + + In some cases, such as rapid traffic surges, Cloud Functions + may, for a short period of time, create more instances than + the specified max instances limit. If your function cannot + tolerate this temporary behavior, you may want to factor in + a safety margin and set a lower max instances value than + your function can tolerate. + + See the `Max + Instances `__ + Guide for more details. + min_instances (int): + A lower bound for the number function + instances that may coexist at a given time. + vpc_connector (str): + The VPC Network Connector that this cloud function can + connect to. It can be either the fully-qualified URI, or the + short name of the network connector resource. The format of + this field is ``projects/*/locations/*/connectors/*`` + + This field is mutually exclusive with ``network`` field and + will eventually replace it. + + See `the VPC + documentation `__ + for more information on connecting Cloud projects. + vpc_connector_egress_settings (google.cloud.functions_v1.types.CloudFunction.VpcConnectorEgressSettings): + The egress settings for the connector, + controlling what traffic is diverted through it. + ingress_settings (google.cloud.functions_v1.types.CloudFunction.IngressSettings): + The ingress settings for the function, + controlling what traffic can reach it. + kms_key_name (str): + Resource name of a KMS crypto key (managed by the user) used + to encrypt/decrypt function resources. + + It must match the pattern + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. + + If specified, you must also provide an artifact registry + repository using the ``docker_repository`` field that was + created with the same KMS crypto key. + + The following service accounts need to be granted the role + 'Cloud KMS CryptoKey Encrypter/Decrypter + (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the + Key/KeyRing/Project/Organization (least access preferred). + + 1. Google Cloud Functions service account + (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) + - Required to protect the function's image. + 2. Google Storage service account + (service-{project_number}@gs-project-accounts.iam.gserviceaccount.com) + - Required to protect the function's source code. If this + service account does not exist, deploying a function + without a KMS key or retrieving the service agent name + provisions it. For more information, see + https://cloud.google.com/storage/docs/projects#service-agents + and + https://cloud.google.com/storage/docs/getting-service-agent#gsutil. + + Google Cloud Functions delegates access to service agents to + protect function resources in internal projects that are not + accessible by the end user. + build_worker_pool (str): + Name of the Cloud Build Custom Worker Pool that should be + used to build the function. The format of this field is + ``projects/{project}/locations/{region}/workerPools/{workerPool}`` + where ``{project}`` and ``{region}`` are the project id and + region respectively where the worker pool is defined and + ``{workerPool}`` is the short name of the worker pool. + + If the project id is not the same as the function, then the + Cloud Functions Service Agent + (``service-@gcf-admin-robot.iam.gserviceaccount.com``) + must be granted the role Cloud Build Custom Workers Builder + (``roles/cloudbuild.customworkers.builder``) in the project. + build_id (str): + Output only. The Cloud Build ID of the latest + successful deployment of the function. + build_name (str): + Output only. The Cloud Build Name of the function + deployment. + ``projects//locations//builds/``. + secret_environment_variables (Sequence[google.cloud.functions_v1.types.SecretEnvVar]): + Secret environment variables configuration. + secret_volumes (Sequence[google.cloud.functions_v1.types.SecretVolume]): + Secret volumes configuration. + source_token (str): + Input only. An identifier for Firebase + function sources. Disclaimer: This field is only + supported for Firebase function deployments. + docker_repository (str): + User managed repository created in Artifact Registry + optionally with a customer managed encryption key. If + specified, deployments will use Artifact Registry. If + unspecified and the deployment is eligible to use Artifact + Registry, GCF will create and use a repository named + 'gcf-artifacts' for every deployed region. This is the + repository to which the function docker image will be pushed + after it is built by Cloud Build. + + It must match the pattern + ``projects/{project}/locations/{location}/repositories/{repository}``. + + Cross-project repositories are not supported. Cross-location + repositories are not supported. Repository format must be + 'DOCKER'. + docker_registry (google.cloud.functions_v1.types.CloudFunction.DockerRegistry): + Docker Registry to use for this deployment. + + If ``docker_repository`` field is specified, this field will + be automatically set as ``ARTIFACT_REGISTRY``. If + unspecified, it currently defaults to + ``CONTAINER_REGISTRY``. This field may be overridden by the + backend for eligible deployments. + """ + class VpcConnectorEgressSettings(proto.Enum): + r"""Available egress settings. + + This controls what traffic is diverted through the VPC Access + Connector resource. By default PRIVATE_RANGES_ONLY will be used. + """ + VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED = 0 + PRIVATE_RANGES_ONLY = 1 + ALL_TRAFFIC = 2 + + class IngressSettings(proto.Enum): + r"""Available ingress settings. + + This controls what traffic can reach the function. + + If unspecified, ALLOW_ALL will be used. + """ + INGRESS_SETTINGS_UNSPECIFIED = 0 + ALLOW_ALL = 1 + ALLOW_INTERNAL_ONLY = 2 + ALLOW_INTERNAL_AND_GCLB = 3 + + class DockerRegistry(proto.Enum): + r"""Docker Registry to use for storing function Docker images.""" + DOCKER_REGISTRY_UNSPECIFIED = 0 + CONTAINER_REGISTRY = 1 + ARTIFACT_REGISTRY = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + source_archive_url = proto.Field( + proto.STRING, + number=3, + oneof='source_code', + ) + source_repository = proto.Field( + proto.MESSAGE, + number=4, + oneof='source_code', + message='SourceRepository', + ) + source_upload_url = proto.Field( + proto.STRING, + number=16, + oneof='source_code', + ) + https_trigger = proto.Field( + proto.MESSAGE, + number=5, + oneof='trigger', + message='HttpsTrigger', + ) + event_trigger = proto.Field( + proto.MESSAGE, + number=6, + oneof='trigger', + message='EventTrigger', + ) + status = proto.Field( + proto.ENUM, + number=7, + enum='CloudFunctionStatus', + ) + entry_point = proto.Field( + proto.STRING, + number=8, + ) + runtime = proto.Field( + proto.STRING, + number=19, + ) + timeout = proto.Field( + proto.MESSAGE, + number=9, + message=duration_pb2.Duration, + ) + available_memory_mb = proto.Field( + proto.INT32, + number=10, + ) + service_account_email = proto.Field( + proto.STRING, + number=11, + ) + update_time = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + version_id = proto.Field( + proto.INT64, + number=14, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=15, + ) + environment_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=17, + ) + build_environment_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=28, + ) + network = proto.Field( + proto.STRING, + number=18, + ) + max_instances = proto.Field( + proto.INT32, + number=20, + ) + min_instances = proto.Field( + proto.INT32, + number=32, + ) + vpc_connector = proto.Field( + proto.STRING, + number=22, + ) + vpc_connector_egress_settings = proto.Field( + proto.ENUM, + number=23, + enum=VpcConnectorEgressSettings, + ) + ingress_settings = proto.Field( + proto.ENUM, + number=24, + enum=IngressSettings, + ) + kms_key_name = proto.Field( + proto.STRING, + number=25, + ) + build_worker_pool = proto.Field( + proto.STRING, + number=26, + ) + build_id = proto.Field( + proto.STRING, + number=27, + ) + build_name = proto.Field( + proto.STRING, + number=33, + ) + secret_environment_variables = proto.RepeatedField( + proto.MESSAGE, + number=29, + message='SecretEnvVar', + ) + secret_volumes = proto.RepeatedField( + proto.MESSAGE, + number=30, + message='SecretVolume', + ) + source_token = proto.Field( + proto.STRING, + number=31, + ) + docker_repository = proto.Field( + proto.STRING, + number=34, + ) + docker_registry = proto.Field( + proto.ENUM, + number=35, + enum=DockerRegistry, + ) + + +class SourceRepository(proto.Message): + r"""Describes SourceRepository, used to represent parameters + related to source repository where a function is hosted. + + Attributes: + url (str): + The URL pointing to the hosted repository where the function + is defined. There are supported Cloud Source Repository URLs + in the following formats: + + To refer to a specific commit: + ``https://source.developers.google.com/projects/*/repos/*/revisions/*/paths/*`` + To refer to a moveable alias (branch): + ``https://source.developers.google.com/projects/*/repos/*/moveable-aliases/*/paths/*`` + In particular, to refer to HEAD use ``master`` moveable + alias. To refer to a specific fixed alias (tag): + ``https://source.developers.google.com/projects/*/repos/*/fixed-aliases/*/paths/*`` + + You may omit ``paths/*`` if you want to use the main + directory. + deployed_url (str): + Output only. The URL pointing to the hosted + repository where the function were defined at + the time of deployment. It always points to a + specific commit in the format described above. + """ + + url = proto.Field( + proto.STRING, + number=1, + ) + deployed_url = proto.Field( + proto.STRING, + number=2, + ) + + +class HttpsTrigger(proto.Message): + r"""Describes HttpsTrigger, could be used to connect web hooks to + function. + + Attributes: + url (str): + Output only. The deployed url for the + function. + security_level (google.cloud.functions_v1.types.HttpsTrigger.SecurityLevel): + The security level for the function. + """ + class SecurityLevel(proto.Enum): + r"""Available security level settings. + + This controls the methods to enforce security (HTTPS) on a URL. + + If unspecified, SECURE_OPTIONAL will be used. + """ + SECURITY_LEVEL_UNSPECIFIED = 0 + SECURE_ALWAYS = 1 + SECURE_OPTIONAL = 2 + + url = proto.Field( + proto.STRING, + number=1, + ) + security_level = proto.Field( + proto.ENUM, + number=2, + enum=SecurityLevel, + ) + + +class EventTrigger(proto.Message): + r"""Describes EventTrigger, used to request events be sent from + another service. + + Attributes: + event_type (str): + Required. The type of event to observe. For example: + ``providers/cloud.storage/eventTypes/object.change`` and + ``providers/cloud.pubsub/eventTypes/topic.publish``. + + Event types match pattern ``providers/*/eventTypes/*.*``. + The pattern contains: + + 1. namespace: For example, ``cloud.storage`` and + ``google.firebase.analytics``. + 2. resource type: The type of resource on which event + occurs. For example, the Google Cloud Storage API + includes the type ``object``. + 3. action: The action that generates the event. For example, + action for a Google Cloud Storage Object is 'change'. + These parts are lower case. + resource (str): + Required. The resource(s) from which to observe events, for + example, ``projects/_/buckets/myBucket``. + + Not all syntactically correct values are accepted by all + services. For example: + + 1. The authorization model must support it. Google Cloud + Functions only allows EventTriggers to be deployed that + observe resources in the same project as the + ``CloudFunction``. + 2. The resource type must match the pattern expected for an + ``event_type``. For example, an ``EventTrigger`` that has + an ``event_type`` of "google.pubsub.topic.publish" should + have a resource that matches Google Cloud Pub/Sub topics. + + Additionally, some services may support short names when + creating an ``EventTrigger``. These will always be returned + in the normalized "long" format. + + See each *service's* documentation for supported formats. + service (str): + The hostname of the service that should be observed. + + If no string is provided, the default service implementing + the API will be used. For example, + ``storage.googleapis.com`` is the default for all event + types in the ``google.storage`` namespace. + failure_policy (google.cloud.functions_v1.types.FailurePolicy): + Specifies policy for failed executions. + """ + + event_type = proto.Field( + proto.STRING, + number=1, + ) + resource = proto.Field( + proto.STRING, + number=2, + ) + service = proto.Field( + proto.STRING, + number=3, + ) + failure_policy = proto.Field( + proto.MESSAGE, + number=5, + message='FailurePolicy', + ) + + +class FailurePolicy(proto.Message): + r"""Describes the policy in case of function's execution failure. + If empty, then defaults to ignoring failures (i.e. not retrying + them). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + retry (google.cloud.functions_v1.types.FailurePolicy.Retry): + If specified, then the function will be + retried in case of a failure. + + This field is a member of `oneof`_ ``action``. + """ + + class Retry(proto.Message): + r"""Describes the retry policy in case of function's execution + failure. A function execution will be retried on any failure. A + failed execution will be retried up to 7 days with an + exponential backoff (capped at 10 seconds). + Retried execution is charged as any other execution. + + """ + + retry = proto.Field( + proto.MESSAGE, + number=1, + oneof='action', + message=Retry, + ) + + +class SecretEnvVar(proto.Message): + r"""Configuration for a secret environment variable. It has the + information necessary to fetch the secret value from secret + manager and expose it as an environment variable. + + Attributes: + key (str): + Name of the environment variable. + project_id (str): + Project identifier (preferrably project + number but can also be the project ID) of the + project that contains the secret. If not set, it + will be populated with the function's project + assuming that the secret exists in the same + project as of the function. + secret (str): + Name of the secret in secret manager (not the + full resource name). + version (str): + Version of the secret (version number or the + string 'latest'). It is recommended to use a + numeric version for secret environment variables + as any updates to the secret value is not + reflected until new instances start. + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + secret = proto.Field( + proto.STRING, + number=3, + ) + version = proto.Field( + proto.STRING, + number=4, + ) + + +class SecretVolume(proto.Message): + r"""Configuration for a secret volume. It has the information + necessary to fetch the secret value from secret manager and make + it available as files mounted at the requested paths within the + application container. Secret value is not a part of the + configuration. Every filesystem read operation performs a lookup + in secret manager to retrieve the secret value. + + Attributes: + mount_path (str): + The path within the container to mount the secret volume. + For example, setting the mount_path as ``/etc/secrets`` + would mount the secret value files under the + ``/etc/secrets`` directory. This directory will also be + completely shadowed and unavailable to mount any other + secrets. + + Recommended mount paths: /etc/secrets Restricted mount + paths: /cloudsql, /dev/log, /pod, /proc, /var/log + project_id (str): + Project identifier (preferrably project + number but can also be the project ID) of the + project that contains the secret. If not set, it + will be populated with the function's project + assuming that the secret exists in the same + project as of the function. + secret (str): + Name of the secret in secret manager (not the + full resource name). + versions (Sequence[google.cloud.functions_v1.types.SecretVolume.SecretVersion]): + List of secret versions to mount for this secret. If empty, + the ``latest`` version of the secret will be made available + in a file named after the secret under the mount point. + """ + + class SecretVersion(proto.Message): + r"""Configuration for a single version. + + Attributes: + version (str): + Version of the secret (version number or the string + 'latest'). It is preferrable to use ``latest`` version with + secret volumes as secret value changes are reflected + immediately. + path (str): + Relative path of the file under the mount path where the + secret value for this version will be fetched and made + available. For example, setting the mount_path as + '/etc/secrets' and path as ``/secret_foo`` would mount the + secret value file at ``/etc/secrets/secret_foo``. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + path = proto.Field( + proto.STRING, + number=2, + ) + + mount_path = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + secret = proto.Field( + proto.STRING, + number=3, + ) + versions = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=SecretVersion, + ) + + +class CreateFunctionRequest(proto.Message): + r"""Request for the ``CreateFunction`` method. + + Attributes: + location (str): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + function (google.cloud.functions_v1.types.CloudFunction): + Required. Function to be created. + """ + + location = proto.Field( + proto.STRING, + number=1, + ) + function = proto.Field( + proto.MESSAGE, + number=2, + message='CloudFunction', + ) + + +class UpdateFunctionRequest(proto.Message): + r"""Request for the ``UpdateFunction`` method. + + Attributes: + function (google.cloud.functions_v1.types.CloudFunction): + Required. New version of the function. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields in ``CloudFunction`` that have + to be updated. + """ + + function = proto.Field( + proto.MESSAGE, + number=1, + message='CloudFunction', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetFunctionRequest(proto.Message): + r"""Request for the ``GetFunction`` method. + + Attributes: + name (str): + Required. The name of the function which + details should be obtained. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFunctionsRequest(proto.Message): + r"""Request for the ``ListFunctions`` method. + + Attributes: + parent (str): + The project and location from which the function should be + listed, specified in the format ``projects/*/locations/*`` + If you want to list functions in all locations, use "-" in + place of a location. When listing functions in all + locations, if one or more location(s) are unreachable, the + response will contain functions from all reachable locations + along with the names of any unreachable locations. + page_size (int): + Maximum number of functions to return per + call. + page_token (str): + The value returned by the last ``ListFunctionsResponse``; + indicates that this is a continuation of a prior + ``ListFunctions`` call, and that the system should return + the next page of data. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListFunctionsResponse(proto.Message): + r"""Response for the ``ListFunctions`` method. + + Attributes: + functions (Sequence[google.cloud.functions_v1.types.CloudFunction]): + The functions that match the request. + next_page_token (str): + If not empty, indicates that there may be more functions + that match the request; this value should be passed in a new + [google.cloud.functions.v1.ListFunctionsRequest][google.cloud.functions.v1.ListFunctionsRequest] + to get more functions. + unreachable (Sequence[str]): + Locations that could not be reached. The + response does not include any functions from + these locations. + """ + + @property + def raw_page(self): + return self + + functions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CloudFunction', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + unreachable = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DeleteFunctionRequest(proto.Message): + r"""Request for the ``DeleteFunction`` method. + + Attributes: + name (str): + Required. The name of the function which + should be deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CallFunctionRequest(proto.Message): + r"""Request for the ``CallFunction`` method. + + Attributes: + name (str): + Required. The name of the function to be + called. + data (str): + Required. Input to be passed to the function. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + data = proto.Field( + proto.STRING, + number=2, + ) + + +class CallFunctionResponse(proto.Message): + r"""Response of ``CallFunction`` method. + + Attributes: + execution_id (str): + Execution id of function invocation. + result (str): + Result populated for successful execution of + synchronous function. Will not be populated if + function does not return a result through + context. + error (str): + Either system or user-function generated + error. Set if execution was not successful. + """ + + execution_id = proto.Field( + proto.STRING, + number=1, + ) + result = proto.Field( + proto.STRING, + number=2, + ) + error = proto.Field( + proto.STRING, + number=3, + ) + + +class GenerateUploadUrlRequest(proto.Message): + r"""Request of ``GenerateSourceUploadUrl`` method. + + Attributes: + parent (str): + The project and location in which the Google Cloud Storage + signed URL should be generated, specified in the format + ``projects/*/locations/*``. + kms_key_name (str): + Resource name of a KMS crypto key (managed by the user) used + to encrypt/decrypt function source code objects in staging + Cloud Storage buckets. When you generate an upload url and + upload your source code, it gets copied to a staging Cloud + Storage bucket in an internal regional project. The source + code is then copied to a versioned directory in the sources + bucket in the consumer project during the function + deployment. + + It must match the pattern + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. + + The Google Cloud Functions service account + (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) + must be granted the role 'Cloud KMS CryptoKey + Encrypter/Decrypter + (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the + Key/KeyRing/Project/Organization (least access preferred). + GCF will delegate access to the Google Storage service + account in the internal project. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + kms_key_name = proto.Field( + proto.STRING, + number=2, + ) + + +class GenerateUploadUrlResponse(proto.Message): + r"""Response of ``GenerateSourceUploadUrl`` method. + + Attributes: + upload_url (str): + The generated Google Cloud Storage signed URL + that should be used for a function source code + upload. The uploaded file should be a zip + archive which contains a function. + """ + + upload_url = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateDownloadUrlRequest(proto.Message): + r"""Request of ``GenerateDownloadUrl`` method. + + Attributes: + name (str): + The name of function for which source code + Google Cloud Storage signed URL should be + generated. + version_id (int): + The optional version of function. If not set, + default, current version is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + version_id = proto.Field( + proto.UINT64, + number=2, + ) + + +class GenerateDownloadUrlResponse(proto.Message): + r"""Response of ``GenerateDownloadUrl`` method. + + Attributes: + download_url (str): + The generated Google Cloud Storage signed URL + that should be used for function source code + download. + """ + + download_url = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py new file mode 100644 index 0000000..ab59796 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py @@ -0,0 +1,108 @@ +# -*- 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 any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.functions.v1', + manifest={ + 'OperationType', + 'OperationMetadataV1', + }, +) + + +class OperationType(proto.Enum): + r"""A type of an operation.""" + OPERATION_UNSPECIFIED = 0 + CREATE_FUNCTION = 1 + UPDATE_FUNCTION = 2 + DELETE_FUNCTION = 3 + + +class OperationMetadataV1(proto.Message): + r"""Metadata describing an [Operation][google.longrunning.Operation] + + Attributes: + target (str): + Target of the operation - for example + ``projects/project-1/locations/region-1/functions/function-1`` + type_ (google.cloud.functions_v1.types.OperationType): + Type of operation. + request (google.protobuf.any_pb2.Any): + The original request that started the + operation. + version_id (int): + Version id of the function created or updated + by an API call. This field is only populated for + Create and Update operations. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update timestamp of the operation. + build_id (str): + The Cloud Build ID of the function created or + updated by an API call. This field is only + populated for Create and Update operations. + source_token (str): + An identifier for Firebase function sources. + Disclaimer: This field is only supported for + Firebase function deployments. + build_name (str): + The Cloud Build Name of the function deployment. This field + is only populated for Create and Update operations. + ``projects//locations//builds/``. + """ + + target = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum='OperationType', + ) + request = proto.Field( + proto.MESSAGE, + number=3, + message=any_pb2.Any, + ) + version_id = proto.Field( + proto.INT64, + number=4, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + build_id = proto.Field( + proto.STRING, + number=6, + ) + source_token = proto.Field( + proto.STRING, + number=7, + ) + build_name = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..38940e8 --- /dev/null +++ b/owl-bot-staging/v1/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', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/functions_v1/', + '--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/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py new file mode 100644 index 0000000..f6b67dc --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] +from google.cloud import functions_v1 + + +async def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = await client.call_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py new file mode 100644 index 0000000..7cddbe7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] +from google.cloud import functions_v1 + + +def sample_call_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.CallFunctionRequest( + name="name_value", + data="data_value", + ) + + # Make the request + response = client.call_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py new file mode 100644 index 0000000..dd6b621 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py @@ -0,0 +1,53 @@ +# -*- 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 CreateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] +from google.cloud import functions_v1 + + +async def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py new file mode 100644 index 0000000..117d443 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py @@ -0,0 +1,53 @@ +# -*- 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 CreateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] +from google.cloud import functions_v1 + + +def sample_create_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.CreateFunctionRequest( + location="location_value", + function=function, + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py new file mode 100644 index 0000000..3051534 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] +from google.cloud import functions_v1 + + +async def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py new file mode 100644 index 0000000..2262e7b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] +from google.cloud import functions_v1 + + +def sample_delete_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py new file mode 100644 index 0000000..30f6889 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateDownloadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] +from google.cloud import functions_v1 + + +async def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = await client.generate_download_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py new file mode 100644 index 0000000..fbc886f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateDownloadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] +from google.cloud import functions_v1 + + +def sample_generate_download_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateDownloadUrlRequest( + ) + + # Make the request + response = client.generate_download_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py new file mode 100644 index 0000000..6b19431 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateUploadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] +from google.cloud import functions_v1 + + +async def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = await client.generate_upload_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py new file mode 100644 index 0000000..6e9590a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py @@ -0,0 +1,44 @@ +# -*- 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 GenerateUploadUrl +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] +from google.cloud import functions_v1 + + +def sample_generate_upload_url(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GenerateUploadUrlRequest( + ) + + # Make the request + response = client.generate_upload_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py new file mode 100644 index 0000000..f89b7da --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] +from google.cloud import functions_v1 + + +async def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py new file mode 100644 index 0000000..761c41d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] +from google.cloud import functions_v1 + + +def sample_get_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = client.get_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py new file mode 100644 index 0000000..09d1b8a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py new file mode 100644 index 0000000..eafe7b7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py new file mode 100644 index 0000000..9a3cd36 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] +from google.cloud import functions_v1 + + +async def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py new file mode 100644 index 0000000..98b3760 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] +from google.cloud import functions_v1 + + +def sample_list_functions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = functions_v1.ListFunctionsRequest( + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py new file mode 100644 index 0000000..2d1128e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py new file mode 100644 index 0000000..b8b14ab --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py new file mode 100644 index 0000000..936744f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py @@ -0,0 +1,47 @@ +# -*- 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py new file mode 100644 index 0000000..c5766f3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py @@ -0,0 +1,47 @@ +# -*- 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] +from google.cloud import functions_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py new file mode 100644 index 0000000..4863198 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py @@ -0,0 +1,52 @@ +# -*- 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 UpdateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] +from google.cloud import functions_v1 + + +async def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceAsyncClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py new file mode 100644 index 0000000..11809c3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py @@ -0,0 +1,52 @@ +# -*- 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 UpdateFunction +# 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-functions + + +# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] +from google.cloud import functions_v1 + + +def sample_update_function(): + # Create a client + client = functions_v1.CloudFunctionsServiceClient() + + # Initialize request argument(s) + function = functions_v1.CloudFunction() + function.source_archive_url = "source_archive_url_value" + + request = functions_v1.UpdateFunctionRequest( + function=function, + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json new file mode 100644 index 0000000..9c991cf --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json @@ -0,0 +1,1753 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.functions.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-functions" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.call_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CallFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CallFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "data", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", + "shortName": "call_function" + }, + "description": "Sample for CallFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.call_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CallFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CallFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "data", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", + "shortName": "call_function" + }, + "description": "Sample for CallFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.create_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CreateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CreateFunctionRequest" + }, + { + "name": "location", + "type": "str" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_function" + }, + "description": "Sample for CreateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.create_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "CreateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.CreateFunctionRequest" + }, + { + "name": "location", + "type": "str" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_function" + }, + "description": "Sample for CreateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.delete_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "DeleteFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_function" + }, + "description": "Sample for DeleteFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.delete_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "DeleteFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_function" + }, + "description": "Sample for DeleteFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_download_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateDownloadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", + "shortName": "generate_download_url" + }, + "description": "Sample for GenerateDownloadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_download_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateDownloadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", + "shortName": "generate_download_url" + }, + "description": "Sample for GenerateDownloadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_upload_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateUploadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", + "shortName": "generate_upload_url" + }, + "description": "Sample for GenerateUploadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_upload_url", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GenerateUploadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", + "shortName": "generate_upload_url" + }, + "description": "Sample for GenerateUploadUrl", + "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GetFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CloudFunction", + "shortName": "get_function" + }, + "description": "Sample for GetFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.GetFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.types.CloudFunction", + "shortName": "get_function" + }, + "description": "Sample for GetFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.list_functions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "ListFunctions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.ListFunctionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager", + "shortName": "list_functions" + }, + "description": "Sample for ListFunctions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.list_functions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "ListFunctions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.ListFunctionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager", + "shortName": "list_functions" + }, + "description": "Sample for ListFunctions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.set_iam_policy", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 43, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 44, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync", + "segments": [ + { + "end": 46, + "start": 27, + "type": "FULL" + }, + { + "end": 46, + "start": 27, + "type": "SHORT" + }, + { + "end": 34, + "start": 32, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 40, + "start": 35, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 43, + "start": 41, + "type": "REQUEST_EXECUTION" + }, + { + "end": 47, + "start": 44, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", + "shortName": "CloudFunctionsServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.update_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "UpdateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_function" + }, + "description": "Sample for UpdateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", + "shortName": "CloudFunctionsServiceClient" + }, + "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.update_function", + "method": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", + "service": { + "fullName": "google.cloud.functions.v1.CloudFunctionsService", + "shortName": "CloudFunctionsService" + }, + "shortName": "UpdateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" + }, + { + "name": "function", + "type": "google.cloud.functions_v1.types.CloudFunction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_function" + }, + "description": "Sample for UpdateFunction", + "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py new file mode 100644 index 0000000..6dc057c --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_functions_v1_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 functionsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'call_function': ('name', 'data', ), + 'create_function': ('location', 'function', ), + 'delete_function': ('name', ), + 'generate_download_url': ('name', 'version_id', ), + 'generate_upload_url': ('parent', 'kms_key_name', ), + 'get_function': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'list_functions': ('parent', 'page_size', 'page_token', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_function': ('function', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=functionsCallTransformer(), +): + """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 functions client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..820b19a --- /dev/null +++ b/owl-bot-staging/v1/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-functions', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-functions", + 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] >= 2.8.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.4, < 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/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/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/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/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/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/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/v1/tests/unit/gapic/functions_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__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/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py new file mode 100644 index 0000000..86b090e --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py @@ -0,0 +1,3681 @@ +# -*- 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 +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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.functions_v1.services.cloud_functions_service import CloudFunctionsServiceAsyncClient +from google.cloud.functions_v1.services.cloud_functions_service import CloudFunctionsServiceClient +from google.cloud.functions_v1.services.cloud_functions_service import pagers +from google.cloud.functions_v1.services.cloud_functions_service import transports +from google.cloud.functions_v1.types import functions +from google.cloud.functions_v1.types import operations +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 CloudFunctionsServiceClient._get_default_mtls_endpoint(None) is None + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CloudFunctionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CloudFunctionsServiceClient, "grpc"), + (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CloudFunctionsServiceGrpcTransport, "grpc"), + (transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CloudFunctionsServiceClient, "grpc"), + (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + + +def test_cloud_functions_service_client_get_transport_class(): + transport = CloudFunctionsServiceClient.get_transport_class() + available_transports = [ + transports.CloudFunctionsServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CloudFunctionsServiceClient.get_transport_class("grpc") + assert transport == transports.CloudFunctionsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) +@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) +def test_cloud_functions_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(CloudFunctionsServiceClient, '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(CloudFunctionsServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + 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, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "true"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "false"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) +@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_functions_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CloudFunctionsServiceClient, CloudFunctionsServiceAsyncClient +]) +@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) +@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) +def test_cloud_functions_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_cloud_functions_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_cloud_functions_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_cloud_functions_service_client_client_options_from_dict(): + with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CloudFunctionsServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_cloud_functions_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudfunctions.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="cloudfunctions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + functions.ListFunctionsRequest, + dict, +]) +def test_list_functions(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_functions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListFunctionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFunctionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_functions_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 = CloudFunctionsServiceClient( + 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_functions), + '__call__') as call: + client.list_functions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + +@pytest.mark.asyncio +async def test_list_functions_async(transport: str = 'grpc_asyncio', request_type=functions.ListFunctionsRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_functions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFunctionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_functions_async_from_dict(): + await test_list_functions_async(request_type=dict) + + +def test_list_functions_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListFunctionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__') as call: + call.return_value = functions.ListFunctionsResponse() + client.list_functions(request) + + # Establish that the 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_functions_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListFunctionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse()) + await client.list_functions(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_functions_pager(transport_name: str = "grpc"): + client = CloudFunctionsServiceClient( + 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_functions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_functions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, functions.CloudFunction) + for i in results) +def test_list_functions_pages(transport_name: str = "grpc"): + client = CloudFunctionsServiceClient( + 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_functions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + pages = list(client.list_functions(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_functions_async_pager(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_functions(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, functions.CloudFunction) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_functions_async_pages(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + functions.CloudFunction(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.CloudFunction(), + functions.CloudFunction(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_functions(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", [ + functions.GetFunctionRequest, + dict, +]) +def test_get_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CloudFunction( + name='name_value', + description='description_value', + status=functions.CloudFunctionStatus.ACTIVE, + entry_point='entry_point_value', + runtime='runtime_value', + available_memory_mb=1991, + service_account_email='service_account_email_value', + version_id=1074, + network='network_value', + max_instances=1389, + min_instances=1387, + vpc_connector='vpc_connector_value', + vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, + ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, + kms_key_name='kms_key_name_value', + build_worker_pool='build_worker_pool_value', + build_id='build_id_value', + build_name='build_name_value', + source_token='source_token_value', + docker_repository='docker_repository_value', + docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, + source_archive_url='source_archive_url_value', + https_trigger=functions.HttpsTrigger(url='url_value'), + ) + response = client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CloudFunction) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.status == functions.CloudFunctionStatus.ACTIVE + assert response.entry_point == 'entry_point_value' + assert response.runtime == 'runtime_value' + assert response.available_memory_mb == 1991 + assert response.service_account_email == 'service_account_email_value' + assert response.version_id == 1074 + assert response.network == 'network_value' + assert response.max_instances == 1389 + assert response.min_instances == 1387 + assert response.vpc_connector == 'vpc_connector_value' + assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY + assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL + assert response.kms_key_name == 'kms_key_name_value' + assert response.build_worker_pool == 'build_worker_pool_value' + assert response.build_id == 'build_id_value' + assert response.build_name == 'build_name_value' + assert response.source_token == 'source_token_value' + assert response.docker_repository == 'docker_repository_value' + assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY + + +def test_get_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.get_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + +@pytest.mark.asyncio +async def test_get_function_async(transport: str = 'grpc_asyncio', request_type=functions.GetFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction( + name='name_value', + description='description_value', + status=functions.CloudFunctionStatus.ACTIVE, + entry_point='entry_point_value', + runtime='runtime_value', + available_memory_mb=1991, + service_account_email='service_account_email_value', + version_id=1074, + network='network_value', + max_instances=1389, + min_instances=1387, + vpc_connector='vpc_connector_value', + vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, + ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, + kms_key_name='kms_key_name_value', + build_worker_pool='build_worker_pool_value', + build_id='build_id_value', + build_name='build_name_value', + source_token='source_token_value', + docker_repository='docker_repository_value', + docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, + )) + response = await client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CloudFunction) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.status == functions.CloudFunctionStatus.ACTIVE + assert response.entry_point == 'entry_point_value' + assert response.runtime == 'runtime_value' + assert response.available_memory_mb == 1991 + assert response.service_account_email == 'service_account_email_value' + assert response.version_id == 1074 + assert response.network == 'network_value' + assert response.max_instances == 1389 + assert response.min_instances == 1387 + assert response.vpc_connector == 'vpc_connector_value' + assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY + assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL + assert response.kms_key_name == 'kms_key_name_value' + assert response.build_worker_pool == 'build_worker_pool_value' + assert response.build_id == 'build_id_value' + assert response.build_name == 'build_name_value' + assert response.source_token == 'source_token_value' + assert response.docker_repository == 'docker_repository_value' + assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY + + +@pytest.mark.asyncio +async def test_get_function_async_from_dict(): + await test_get_function_async(request_type=dict) + + +def test_get_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GetFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + call.return_value = functions.CloudFunction() + client.get_function(request) + + # Establish that the 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_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GetFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) + await client.get_function(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_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CloudFunction() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_function( + 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_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.GetFunctionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CloudFunction() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_function( + 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_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.GetFunctionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.CreateFunctionRequest, + dict, +]) +def test_create_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.create_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + +@pytest.mark.asyncio +async def test_create_function_async(transport: str = 'grpc_asyncio', request_type=functions.CreateFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_function_async_from_dict(): + await test_create_function_async(request_type=dict) + + +def test_create_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CreateFunctionRequest() + + request.location = 'location_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_function(request) + + # Establish that the 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', + 'location=location_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CreateFunctionRequest() + + request.location = 'location_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_function(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', + 'location=location_value', + ) in kw['metadata'] + + +def test_create_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__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_function( + location='location_value', + function=functions.CloudFunction(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].location + mock_val = 'location_value' + assert arg == mock_val + arg = args[0].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + + +def test_create_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.CreateFunctionRequest(), + location='location_value', + function=functions.CloudFunction(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__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_function( + location='location_value', + function=functions.CloudFunction(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].location + mock_val = 'location_value' + assert arg == mock_val + arg = args[0].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.CreateFunctionRequest(), + location='location_value', + function=functions.CloudFunction(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + functions.UpdateFunctionRequest, + dict, +]) +def test_update_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.update_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + +@pytest.mark.asyncio +async def test_update_function_async(transport: str = 'grpc_asyncio', request_type=functions.UpdateFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_function_async_from_dict(): + await test_update_function_async(request_type=dict) + + +def test_update_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.UpdateFunctionRequest() + + request.function.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_function(request) + + # Establish that the 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', + 'function.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.UpdateFunctionRequest() + + request.function.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_function(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', + 'function.name=name_value', + ) in kw['metadata'] + + +def test_update_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__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_function( + function=functions.CloudFunction(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].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + + +def test_update_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.UpdateFunctionRequest(), + function=functions.CloudFunction(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__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_function( + function=functions.CloudFunction(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].function + mock_val = functions.CloudFunction(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.UpdateFunctionRequest(), + function=functions.CloudFunction(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + functions.DeleteFunctionRequest, + dict, +]) +def test_delete_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_function_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 = CloudFunctionsServiceClient( + 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_function), + '__call__') as call: + client.delete_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + +@pytest.mark.asyncio +async def test_delete_function_async(transport: str = 'grpc_asyncio', request_type=functions.DeleteFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_function_async_from_dict(): + await test_delete_function_async(request_type=dict) + + +def test_delete_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.DeleteFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_function(request) + + # Establish that the 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_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.DeleteFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_function(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_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__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_function( + 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_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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_function( + functions.DeleteFunctionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__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_function( + 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_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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_function( + functions.DeleteFunctionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.CallFunctionRequest, + dict, +]) +def test_call_function(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CallFunctionResponse( + execution_id='execution_id_value', + result='result_value', + error='error_value', + ) + response = client.call_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CallFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CallFunctionResponse) + assert response.execution_id == 'execution_id_value' + assert response.result == 'result_value' + assert response.error == 'error_value' + + +def test_call_function_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 = CloudFunctionsServiceClient( + 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.call_function), + '__call__') as call: + client.call_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CallFunctionRequest() + +@pytest.mark.asyncio +async def test_call_function_async(transport: str = 'grpc_asyncio', request_type=functions.CallFunctionRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse( + execution_id='execution_id_value', + result='result_value', + error='error_value', + )) + response = await client.call_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CallFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.CallFunctionResponse) + assert response.execution_id == 'execution_id_value' + assert response.result == 'result_value' + assert response.error == 'error_value' + + +@pytest.mark.asyncio +async def test_call_function_async_from_dict(): + await test_call_function_async(request_type=dict) + + +def test_call_function_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CallFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + call.return_value = functions.CallFunctionResponse() + client.call_function(request) + + # Establish that the 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_call_function_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CallFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) + await client.call_function(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_call_function_flattened(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CallFunctionResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.call_function( + name='name_value', + data='data_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 + arg = args[0].data + mock_val = 'data_value' + assert arg == mock_val + + +def test_call_function_flattened_error(): + client = CloudFunctionsServiceClient( + 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.call_function( + functions.CallFunctionRequest(), + name='name_value', + data='data_value', + ) + +@pytest.mark.asyncio +async def test_call_function_flattened_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.call_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.CallFunctionResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.call_function( + name='name_value', + data='data_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 + arg = args[0].data + mock_val = 'data_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_call_function_flattened_error_async(): + client = CloudFunctionsServiceAsyncClient( + 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.call_function( + functions.CallFunctionRequest(), + name='name_value', + data='data_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.GenerateUploadUrlRequest, + dict, +]) +def test_generate_upload_url(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.GenerateUploadUrlResponse( + upload_url='upload_url_value', + ) + response = client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateUploadUrlResponse) + assert response.upload_url == 'upload_url_value' + + +def test_generate_upload_url_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 = CloudFunctionsServiceClient( + 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.generate_upload_url), + '__call__') as call: + client.generate_upload_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + +@pytest.mark.asyncio +async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateUploadUrlRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse( + upload_url='upload_url_value', + )) + response = await client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateUploadUrlResponse) + assert response.upload_url == 'upload_url_value' + + +@pytest.mark.asyncio +async def test_generate_upload_url_async_from_dict(): + await test_generate_upload_url_async(request_type=dict) + + +def test_generate_upload_url_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateUploadUrlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + call.return_value = functions.GenerateUploadUrlResponse() + client.generate_upload_url(request) + + # Establish that the 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_generate_upload_url_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateUploadUrlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse()) + await client.generate_upload_url(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'] + + +@pytest.mark.parametrize("request_type", [ + functions.GenerateDownloadUrlRequest, + dict, +]) +def test_generate_download_url(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.GenerateDownloadUrlResponse( + download_url='download_url_value', + ) + response = client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateDownloadUrlResponse) + assert response.download_url == 'download_url_value' + + +def test_generate_download_url_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 = CloudFunctionsServiceClient( + 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.generate_download_url), + '__call__') as call: + client.generate_download_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + +@pytest.mark.asyncio +async def test_generate_download_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateDownloadUrlRequest): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse( + download_url='download_url_value', + )) + response = await client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateDownloadUrlResponse) + assert response.download_url == 'download_url_value' + + +@pytest.mark.asyncio +async def test_generate_download_url_async_from_dict(): + await test_generate_download_url_async(request_type=dict) + + +def test_generate_download_url_field_headers(): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateDownloadUrlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + call.return_value = functions.GenerateDownloadUrlResponse() + client.generate_download_url(request) + + # Establish that the 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_generate_download_url_field_headers_async(): + client = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateDownloadUrlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse()) + await client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceClient( + 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.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceClient( + 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.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CloudFunctionsServiceClient( + 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.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudFunctionsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudFunctionsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudFunctionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, +]) +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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudFunctionsServiceGrpcTransport, + ) + +def test_cloud_functions_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudFunctionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_cloud_functions_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CloudFunctionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_functions', + 'get_function', + 'create_function', + 'update_function', + 'delete_function', + 'call_function', + 'generate_upload_url', + 'generate_download_url', + 'set_iam_policy', + 'get_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_cloud_functions_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudFunctionsServiceTransport( + 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_cloud_functions_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudFunctionsServiceTransport() + adc.assert_called_once() + + +def test_cloud_functions_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudFunctionsServiceClient() + 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.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_functions_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_functions_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudFunctionsServiceGrpcTransport, grpc_helpers), + (transports.CloudFunctionsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_cloud_functions_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "cloudfunctions.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="cloudfunctions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) +def test_cloud_functions_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_cloud_functions_service_host_no_port(transport_name): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_cloud_functions_service_host_with_port(transport_name): + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:8000' + ) + +def test_cloud_functions_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudFunctionsServiceGrpcTransport( + 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_cloud_functions_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( + 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.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) +def test_cloud_functions_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) +def test_cloud_functions_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_cloud_functions_service_grpc_lro_client(): + client = CloudFunctionsServiceClient( + 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_cloud_functions_service_grpc_lro_async_client(): + client = CloudFunctionsServiceAsyncClient( + 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_cloud_function_path(): + project = "squid" + location = "clam" + function = "whelk" + expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + actual = CloudFunctionsServiceClient.cloud_function_path(project, location, function) + assert expected == actual + + +def test_parse_cloud_function_path(): + expected = { + "project": "octopus", + "location": "oyster", + "function": "nudibranch", + } + path = CloudFunctionsServiceClient.cloud_function_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_cloud_function_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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_crypto_key_path(path) + assert expected == actual + +def test_repository_path(): + project = "whelk" + location = "octopus" + repository = "oyster" + expected = "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) + actual = CloudFunctionsServiceClient.repository_path(project, location, repository) + assert expected == actual + + +def test_parse_repository_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "repository": "mussel", + } + path = CloudFunctionsServiceClient.repository_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_repository_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CloudFunctionsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = CloudFunctionsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = CloudFunctionsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = CloudFunctionsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CloudFunctionsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = CloudFunctionsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = CloudFunctionsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = CloudFunctionsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CloudFunctionsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = CloudFunctionsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudFunctionsServiceClient.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.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: + client = CloudFunctionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CloudFunctionsServiceClient.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 = CloudFunctionsServiceAsyncClient( + 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 = CloudFunctionsServiceClient( + 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 = CloudFunctionsServiceClient( + 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", [ + (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport), + (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport), +]) +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, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc new file mode 100644 index 0000000..ca93bdf --- /dev/null +++ b/owl-bot-staging/v2/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/functions/__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..3e19820 --- /dev/null +++ b/owl-bot-staging/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/functions *.py +recursive-include google/cloud/functions_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst new file mode 100644 index 0000000..533650a --- /dev/null +++ b/owl-bot-staging/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Functions 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 Functions 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..3464a12 --- /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-functions 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-functions" +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-functions-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-functions.tex", + u"google-cloud-functions 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-functions", + u"Google Cloud Functions 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-functions", + u"google-cloud-functions Documentation", + author, + "google-cloud-functions", + "GAPIC library for Google Cloud Functions 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/functions_v2/function_service.rst b/owl-bot-staging/v2/docs/functions_v2/function_service.rst new file mode 100644 index 0000000..03a5132 --- /dev/null +++ b/owl-bot-staging/v2/docs/functions_v2/function_service.rst @@ -0,0 +1,10 @@ +FunctionService +--------------------------------- + +.. automodule:: google.cloud.functions_v2.services.function_service + :members: + :inherited-members: + +.. automodule:: google.cloud.functions_v2.services.function_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/functions_v2/services.rst b/owl-bot-staging/v2/docs/functions_v2/services.rst new file mode 100644 index 0000000..a2004da --- /dev/null +++ b/owl-bot-staging/v2/docs/functions_v2/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Functions v2 API +========================================== +.. toctree:: + :maxdepth: 2 + + function_service diff --git a/owl-bot-staging/v2/docs/functions_v2/types.rst b/owl-bot-staging/v2/docs/functions_v2/types.rst new file mode 100644 index 0000000..f708365 --- /dev/null +++ b/owl-bot-staging/v2/docs/functions_v2/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Functions v2 API +======================================= + +.. automodule:: google.cloud.functions_v2.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst new file mode 100644 index 0000000..15756cf --- /dev/null +++ b/owl-bot-staging/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + functions_v2/services + functions_v2/types diff --git a/owl-bot-staging/v2/google/cloud/functions/__init__.py b/owl-bot-staging/v2/google/cloud/functions/__init__.py new file mode 100644 index 0000000..34f37ea --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions/__init__.py @@ -0,0 +1,77 @@ +# -*- 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.functions_v2.services.function_service.client import FunctionServiceClient +from google.cloud.functions_v2.services.function_service.async_client import FunctionServiceAsyncClient + +from google.cloud.functions_v2.types.functions import BuildConfig +from google.cloud.functions_v2.types.functions import CreateFunctionRequest +from google.cloud.functions_v2.types.functions import DeleteFunctionRequest +from google.cloud.functions_v2.types.functions import EventFilter +from google.cloud.functions_v2.types.functions import EventTrigger +from google.cloud.functions_v2.types.functions import Function +from google.cloud.functions_v2.types.functions import GenerateDownloadUrlRequest +from google.cloud.functions_v2.types.functions import GenerateDownloadUrlResponse +from google.cloud.functions_v2.types.functions import GenerateUploadUrlRequest +from google.cloud.functions_v2.types.functions import GenerateUploadUrlResponse +from google.cloud.functions_v2.types.functions import GetFunctionRequest +from google.cloud.functions_v2.types.functions import ListFunctionsRequest +from google.cloud.functions_v2.types.functions import ListFunctionsResponse +from google.cloud.functions_v2.types.functions import ListRuntimesRequest +from google.cloud.functions_v2.types.functions import ListRuntimesResponse +from google.cloud.functions_v2.types.functions import OperationMetadata +from google.cloud.functions_v2.types.functions import RepoSource +from google.cloud.functions_v2.types.functions import SecretEnvVar +from google.cloud.functions_v2.types.functions import SecretVolume +from google.cloud.functions_v2.types.functions import ServiceConfig +from google.cloud.functions_v2.types.functions import Source +from google.cloud.functions_v2.types.functions import SourceProvenance +from google.cloud.functions_v2.types.functions import Stage +from google.cloud.functions_v2.types.functions import StateMessage +from google.cloud.functions_v2.types.functions import StorageSource +from google.cloud.functions_v2.types.functions import UpdateFunctionRequest +from google.cloud.functions_v2.types.functions import Environment + +__all__ = ('FunctionServiceClient', + 'FunctionServiceAsyncClient', + 'BuildConfig', + 'CreateFunctionRequest', + 'DeleteFunctionRequest', + 'EventFilter', + 'EventTrigger', + 'Function', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GetFunctionRequest', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'ListRuntimesRequest', + 'ListRuntimesResponse', + 'OperationMetadata', + 'RepoSource', + 'SecretEnvVar', + 'SecretVolume', + 'ServiceConfig', + 'Source', + 'SourceProvenance', + 'Stage', + 'StateMessage', + 'StorageSource', + 'UpdateFunctionRequest', + 'Environment', +) diff --git a/owl-bot-staging/v2/google/cloud/functions/py.typed b/owl-bot-staging/v2/google/cloud/functions/py.typed new file mode 100644 index 0000000..982ebb1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/__init__.py b/owl-bot-staging/v2/google/cloud/functions_v2/__init__.py new file mode 100644 index 0000000..e858335 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/__init__.py @@ -0,0 +1,78 @@ +# -*- 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.function_service import FunctionServiceClient +from .services.function_service import FunctionServiceAsyncClient + +from .types.functions import BuildConfig +from .types.functions import CreateFunctionRequest +from .types.functions import DeleteFunctionRequest +from .types.functions import EventFilter +from .types.functions import EventTrigger +from .types.functions import Function +from .types.functions import GenerateDownloadUrlRequest +from .types.functions import GenerateDownloadUrlResponse +from .types.functions import GenerateUploadUrlRequest +from .types.functions import GenerateUploadUrlResponse +from .types.functions import GetFunctionRequest +from .types.functions import ListFunctionsRequest +from .types.functions import ListFunctionsResponse +from .types.functions import ListRuntimesRequest +from .types.functions import ListRuntimesResponse +from .types.functions import OperationMetadata +from .types.functions import RepoSource +from .types.functions import SecretEnvVar +from .types.functions import SecretVolume +from .types.functions import ServiceConfig +from .types.functions import Source +from .types.functions import SourceProvenance +from .types.functions import Stage +from .types.functions import StateMessage +from .types.functions import StorageSource +from .types.functions import UpdateFunctionRequest +from .types.functions import Environment + +__all__ = ( + 'FunctionServiceAsyncClient', +'BuildConfig', +'CreateFunctionRequest', +'DeleteFunctionRequest', +'Environment', +'EventFilter', +'EventTrigger', +'Function', +'FunctionServiceClient', +'GenerateDownloadUrlRequest', +'GenerateDownloadUrlResponse', +'GenerateUploadUrlRequest', +'GenerateUploadUrlResponse', +'GetFunctionRequest', +'ListFunctionsRequest', +'ListFunctionsResponse', +'ListRuntimesRequest', +'ListRuntimesResponse', +'OperationMetadata', +'RepoSource', +'SecretEnvVar', +'SecretVolume', +'ServiceConfig', +'Source', +'SourceProvenance', +'Stage', +'StateMessage', +'StorageSource', +'UpdateFunctionRequest', +) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/functions_v2/gapic_metadata.json new file mode 100644 index 0000000..a8aa8cb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/gapic_metadata.json @@ -0,0 +1,103 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.functions_v2", + "protoPackage": "google.cloud.functions.v2", + "schema": "1.0", + "services": { + "FunctionService": { + "clients": { + "grpc": { + "libraryClient": "FunctionServiceClient", + "rpcs": { + "CreateFunction": { + "methods": [ + "create_function" + ] + }, + "DeleteFunction": { + "methods": [ + "delete_function" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "generate_download_url" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "generate_upload_url" + ] + }, + "GetFunction": { + "methods": [ + "get_function" + ] + }, + "ListFunctions": { + "methods": [ + "list_functions" + ] + }, + "ListRuntimes": { + "methods": [ + "list_runtimes" + ] + }, + "UpdateFunction": { + "methods": [ + "update_function" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FunctionServiceAsyncClient", + "rpcs": { + "CreateFunction": { + "methods": [ + "create_function" + ] + }, + "DeleteFunction": { + "methods": [ + "delete_function" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "generate_download_url" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "generate_upload_url" + ] + }, + "GetFunction": { + "methods": [ + "get_function" + ] + }, + "ListFunctions": { + "methods": [ + "list_functions" + ] + }, + "ListRuntimes": { + "methods": [ + "list_runtimes" + ] + }, + "UpdateFunction": { + "methods": [ + "update_function" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/py.typed b/owl-bot-staging/v2/google/cloud/functions_v2/py.typed new file mode 100644 index 0000000..982ebb1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/functions_v2/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_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/functions_v2/services/function_service/__init__.py b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/__init__.py new file mode 100644 index 0000000..c8ef801 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/__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 FunctionServiceClient +from .async_client import FunctionServiceAsyncClient + +__all__ = ( + 'FunctionServiceClient', + 'FunctionServiceAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/async_client.py b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/async_client.py new file mode 100644 index 0000000..fd460a0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/async_client.py @@ -0,0 +1,1518 @@ +# -*- 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_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.types import functions +from google.cloud.location import locations_pb2 # type: ignore +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 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import FunctionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport +from .client import FunctionServiceClient + + +class FunctionServiceAsyncClient: + """Google Cloud Functions is used to deploy functions that are executed + by Google in response to various events. Data connected with that + event is passed to a function as the input data. + + A **function** is a resource which describes a function that should + be executed and how it is triggered. + """ + + _client: FunctionServiceClient + + DEFAULT_ENDPOINT = FunctionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FunctionServiceClient.DEFAULT_MTLS_ENDPOINT + + build_path = staticmethod(FunctionServiceClient.build_path) + parse_build_path = staticmethod(FunctionServiceClient.parse_build_path) + channel_path = staticmethod(FunctionServiceClient.channel_path) + parse_channel_path = staticmethod(FunctionServiceClient.parse_channel_path) + connector_path = staticmethod(FunctionServiceClient.connector_path) + parse_connector_path = staticmethod(FunctionServiceClient.parse_connector_path) + function_path = staticmethod(FunctionServiceClient.function_path) + parse_function_path = staticmethod(FunctionServiceClient.parse_function_path) + repository_path = staticmethod(FunctionServiceClient.repository_path) + parse_repository_path = staticmethod(FunctionServiceClient.parse_repository_path) + service_path = staticmethod(FunctionServiceClient.service_path) + parse_service_path = staticmethod(FunctionServiceClient.parse_service_path) + topic_path = staticmethod(FunctionServiceClient.topic_path) + parse_topic_path = staticmethod(FunctionServiceClient.parse_topic_path) + trigger_path = staticmethod(FunctionServiceClient.trigger_path) + parse_trigger_path = staticmethod(FunctionServiceClient.parse_trigger_path) + worker_pool_path = staticmethod(FunctionServiceClient.worker_pool_path) + parse_worker_pool_path = staticmethod(FunctionServiceClient.parse_worker_pool_path) + common_billing_account_path = staticmethod(FunctionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FunctionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FunctionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(FunctionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(FunctionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(FunctionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(FunctionServiceClient.common_project_path) + parse_common_project_path = staticmethod(FunctionServiceClient.parse_common_project_path) + common_location_path = staticmethod(FunctionServiceClient.common_location_path) + parse_common_location_path = staticmethod(FunctionServiceClient.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: + FunctionServiceAsyncClient: The constructed client. + """ + return FunctionServiceClient.from_service_account_info.__func__(FunctionServiceAsyncClient, 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: + FunctionServiceAsyncClient: The constructed client. + """ + return FunctionServiceClient.from_service_account_file.__func__(FunctionServiceAsyncClient, 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 FunctionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> FunctionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + FunctionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(FunctionServiceClient).get_transport_class, type(FunctionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FunctionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the function service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.FunctionServiceTransport]): 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 = FunctionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_function(self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.Function: + r"""Returns a function with the given name from the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_get_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GetFunctionRequest, dict]): + The request object. Request for the `GetFunction` + method. + name (:class:`str`): + Required. The name of the function + which details should be obtained. + + 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.functions_v2.types.Function: + Describes a Cloud Function that + contains user computation executed in + response to an event. It encapsulates + function and trigger configurations. + + """ + # 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 = functions.GetFunctionRequest(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_function, + 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_functions(self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsAsyncPager: + r"""Returns a list of functions that belong to the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_list_functions(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.ListFunctionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.ListFunctionsRequest, dict]): + The request object. Request for the `ListFunctions` + method. + parent (:class:`str`): + Required. The project and location from which the + function should be listed, specified in the format + ``projects/*/locations/*`` If you want to list functions + in all locations, use "-" in place of a location. When + listing functions in all locations, if one or more + location(s) are unreachable, the response will contain + functions from all reachable locations along with the + names of any unreachable locations. + + 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.functions_v2.services.function_service.pagers.ListFunctionsAsyncPager: + Response for the ListFunctions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = functions.ListFunctionsRequest(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_functions, + 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.ListFunctionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_function(self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + parent: str = None, + function: functions.Function = None, + function_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_create_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.CreateFunctionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.CreateFunctionRequest, dict]): + The request object. Request for the `CreateFunction` + method. + parent (:class:`str`): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function (:class:`google.cloud.functions_v2.types.Function`): + Required. Function to be created. + This corresponds to the ``function`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function_id (:class:`str`): + The ID to use for the function, which will become the + final component of the function's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``function_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.functions_v2.types.Function` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulates function and + trigger configurations. + + """ + # 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, function, function_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 = functions.CreateFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if function is not None: + request.function = function + if function_id is not None: + request.function_id = function_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_function, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + functions.Function, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_function(self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.Function = 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 existing function. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_update_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.UpdateFunctionRequest( + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.UpdateFunctionRequest, dict]): + The request object. Request for the `UpdateFunction` + method. + function (:class:`google.cloud.functions_v2.types.Function`): + Required. New version of the + function. + + This corresponds to the ``function`` 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. + If no field mask is provided, all + provided fields in the request will 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.functions_v2.types.Function` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulates function and + trigger configurations. + + """ + # 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([function, 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 = functions.UpdateFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if function is not None: + request.function = function + 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_function, + 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(( + ("function.name", request.function.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, + functions.Function, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_function(self, + request: Union[functions.DeleteFunctionRequest, 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 function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_delete_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.DeleteFunctionRequest, dict]): + The request object. Request for the `DeleteFunction` + method. + name (:class:`str`): + Required. The name of the function + which should be deleted. + + 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.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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 = functions.DeleteFunctionRequest(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_function, + 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, + empty_pb2.Empty, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_upload_url(self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: + r"""Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_generate_upload_url(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GenerateUploadUrlRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_upload_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GenerateUploadUrlRequest, dict]): + The request object. Request of `GenerateSourceUploadUrl` + 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.cloud.functions_v2.types.GenerateUploadUrlResponse: + Response of GenerateSourceUploadUrl method. + """ + # Create or coerce a protobuf request object. + request = functions.GenerateUploadUrlRequest(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.generate_upload_url, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_download_url(self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: + r"""Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within 30 minutes of + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_generate_download_url(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GenerateDownloadUrlRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_download_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GenerateDownloadUrlRequest, dict]): + The request object. Request of `GenerateDownloadUrl` + 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.cloud.functions_v2.types.GenerateDownloadUrlResponse: + Response of GenerateDownloadUrl method. + """ + # Create or coerce a protobuf request object. + request = functions.GenerateDownloadUrlRequest(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.generate_download_url, + 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_runtimes(self, + request: Union[functions.ListRuntimesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.ListRuntimesResponse: + r"""Returns a list of runtimes that are supported for the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_list_runtimes(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.ListRuntimesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_runtimes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.ListRuntimesRequest, dict]): + The request object. Request for the `ListRuntimes` + method. + parent (:class:`str`): + Required. The project and location from which the + runtimes should be listed, specified in the format + ``projects/*/locations/*`` + + 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.functions_v2.types.ListRuntimesResponse: + Response for the ListRuntimes method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 = functions.ListRuntimesRequest(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_runtimes, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: operations_pb2.ListOperationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + 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 get_operation( + self, + request: operations_pb2.GetOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + 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 set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest = 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 on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.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 get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.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 test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.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 list_locations( + self, + request: locations_pb2.ListLocationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FunctionServiceAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/client.py b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/client.py new file mode 100644 index 0000000..f9457ef --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/client.py @@ -0,0 +1,1787 @@ +# -*- 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_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.types import functions +from google.cloud.location import locations_pb2 # type: ignore +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 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import FunctionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FunctionServiceGrpcTransport +from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport + + +class FunctionServiceClientMeta(type): + """Metaclass for the FunctionService 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[FunctionServiceTransport]] + _transport_registry["grpc"] = FunctionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = FunctionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[FunctionServiceTransport]: + """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 FunctionServiceClient(metaclass=FunctionServiceClientMeta): + """Google Cloud Functions is used to deploy functions that are executed + by Google in response to various events. Data connected with that + event is passed to a function as the input data. + + A **function** is a resource which describes a function that should + be executed and how it is triggered. + """ + + @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 = "cloudfunctions.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: + FunctionServiceClient: 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: + FunctionServiceClient: 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) -> FunctionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + FunctionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def build_path(project: str,location: str,build: str,) -> str: + """Returns a fully-qualified build string.""" + return "projects/{project}/locations/{location}/builds/{build}".format(project=project, location=location, build=build, ) + + @staticmethod + def parse_build_path(path: str) -> Dict[str,str]: + """Parses a build path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/builds/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def channel_path(project: str,location: str,channel: str,) -> str: + """Returns a fully-qualified channel string.""" + return "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) + + @staticmethod + def parse_channel_path(path: str) -> Dict[str,str]: + """Parses a channel path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", path) + return m.groupdict() if m else {} + + @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 function_path(project: str,location: str,function: str,) -> str: + """Returns a fully-qualified function string.""" + return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + + @staticmethod + def parse_function_path(path: str) -> Dict[str,str]: + """Parses a function path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def repository_path(project: str,location: str,repository: str,) -> str: + """Returns a fully-qualified repository string.""" + return "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) + + @staticmethod + def parse_repository_path(path: str) -> Dict[str,str]: + """Parses a repository path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/repositories/(?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 topic_path(project: str,topic: str,) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str,str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def trigger_path(project: str,location: str,trigger: str,) -> str: + """Returns a fully-qualified trigger string.""" + return "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) + + @staticmethod + def parse_trigger_path(path: str) -> Dict[str,str]: + """Parses a trigger path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def worker_pool_path(project: str,location: str,worker_pool: str,) -> str: + """Returns a fully-qualified worker_pool string.""" + return "projects/{project}/locations/{location}/workerPools/{worker_pool}".format(project=project, location=location, worker_pool=worker_pool, ) + + @staticmethod + def parse_worker_pool_path(path: str) -> Dict[str,str]: + """Parses a worker_pool path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workerPools/(?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, FunctionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the function service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, FunctionServiceTransport]): 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, FunctionServiceTransport): + # transport is a FunctionServiceTransport 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, + api_audience=client_options.api_audience, + ) + + def get_function(self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.Function: + r"""Returns a function with the given name from the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_get_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = client.get_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GetFunctionRequest, dict]): + The request object. Request for the `GetFunction` + method. + name (str): + Required. The name of the function + which details should be obtained. + + 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.functions_v2.types.Function: + Describes a Cloud Function that + contains user computation executed in + response to an event. It encapsulates + function and trigger configurations. + + """ + # 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 functions.GetFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GetFunctionRequest): + request = functions.GetFunctionRequest(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_function] + + # 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_functions(self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsPager: + r"""Returns a list of functions that belong to the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_list_functions(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.ListFunctionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.ListFunctionsRequest, dict]): + The request object. Request for the `ListFunctions` + method. + parent (str): + Required. The project and location from which the + function should be listed, specified in the format + ``projects/*/locations/*`` If you want to list functions + in all locations, use "-" in place of a location. When + listing functions in all locations, if one or more + location(s) are unreachable, the response will contain + functions from all reachable locations along with the + names of any unreachable locations. + + 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.functions_v2.services.function_service.pagers.ListFunctionsPager: + Response for the ListFunctions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a functions.ListFunctionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.ListFunctionsRequest): + request = functions.ListFunctionsRequest(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_functions] + + # 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.ListFunctionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_function(self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + parent: str = None, + function: functions.Function = None, + function_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_create_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.CreateFunctionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.CreateFunctionRequest, dict]): + The request object. Request for the `CreateFunction` + method. + parent (str): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function (google.cloud.functions_v2.types.Function): + Required. Function to be created. + This corresponds to the ``function`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function_id (str): + The ID to use for the function, which will become the + final component of the function's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``function_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.functions_v2.types.Function` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulates function and + trigger configurations. + + """ + # 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, function, function_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 functions.CreateFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.CreateFunctionRequest): + request = functions.CreateFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if function is not None: + request.function = function + if function_id is not None: + request.function_id = function_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_function] + + # 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, + functions.Function, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_function(self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.Function = 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 existing function. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_update_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.UpdateFunctionRequest( + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.UpdateFunctionRequest, dict]): + The request object. Request for the `UpdateFunction` + method. + function (google.cloud.functions_v2.types.Function): + Required. New version of the + function. + + This corresponds to the ``function`` 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. + If no field mask is provided, all + provided fields in the request will 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.functions_v2.types.Function` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulates function and + trigger configurations. + + """ + # 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([function, 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 functions.UpdateFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.UpdateFunctionRequest): + request = functions.UpdateFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if function is not None: + request.function = function + 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_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("function.name", request.function.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, + functions.Function, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_function(self, + request: Union[functions.DeleteFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_delete_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.DeleteFunctionRequest, dict]): + The request object. Request for the `DeleteFunction` + method. + name (str): + Required. The name of the function + which should be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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 functions.DeleteFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.DeleteFunctionRequest): + request = functions.DeleteFunctionRequest(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_function] + + # 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, + empty_pb2.Empty, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_upload_url(self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: + r"""Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_generate_upload_url(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GenerateUploadUrlRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_upload_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GenerateUploadUrlRequest, dict]): + The request object. Request of `GenerateSourceUploadUrl` + 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.cloud.functions_v2.types.GenerateUploadUrlResponse: + Response of GenerateSourceUploadUrl method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.GenerateUploadUrlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GenerateUploadUrlRequest): + request = functions.GenerateUploadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_upload_url] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_download_url(self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: + r"""Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within 30 minutes of + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_generate_download_url(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GenerateDownloadUrlRequest( + name="name_value", + ) + + # Make the request + response = client.generate_download_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GenerateDownloadUrlRequest, dict]): + The request object. Request of `GenerateDownloadUrl` + 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.cloud.functions_v2.types.GenerateDownloadUrlResponse: + Response of GenerateDownloadUrl method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.GenerateDownloadUrlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GenerateDownloadUrlRequest): + request = functions.GenerateDownloadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_download_url] + + # 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_runtimes(self, + request: Union[functions.ListRuntimesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.ListRuntimesResponse: + r"""Returns a list of runtimes that are supported for the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_list_runtimes(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.ListRuntimesRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_runtimes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.ListRuntimesRequest, dict]): + The request object. Request for the `ListRuntimes` + method. + parent (str): + Required. The project and location from which the + runtimes should be listed, specified in the format + ``projects/*/locations/*`` + + 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.functions_v2.types.ListRuntimesResponse: + Response for the ListRuntimes method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 functions.ListRuntimesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.ListRuntimesRequest): + request = functions.ListRuntimesRequest(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_runtimes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __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() + + def list_operations( + self, + request: operations_pb2.ListOperationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: operations_pb2.GetOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest = 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 on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: locations_pb2.ListLocationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + 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 = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FunctionServiceClient", +) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/pagers.py b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/pagers.py new file mode 100644 index 0000000..4e6acec --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/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.functions_v2.types import functions + + +class ListFunctionsPager: + """A pager for iterating through ``list_functions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.functions_v2.types.ListFunctionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``functions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFunctions`` requests and continue to iterate + through the ``functions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.functions_v2.types.ListFunctionsResponse` + 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[..., functions.ListFunctionsResponse], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + 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.functions_v2.types.ListFunctionsRequest): + The initial request object. + response (google.cloud.functions_v2.types.ListFunctionsResponse): + 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 = functions.ListFunctionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[functions.ListFunctionsResponse]: + 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[functions.Function]: + for page in self.pages: + yield from page.functions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFunctionsAsyncPager: + """A pager for iterating through ``list_functions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.functions_v2.types.ListFunctionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``functions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFunctions`` requests and continue to iterate + through the ``functions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.functions_v2.types.ListFunctionsResponse` + 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[functions.ListFunctionsResponse]], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + 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.functions_v2.types.ListFunctionsRequest): + The initial request object. + response (google.cloud.functions_v2.types.ListFunctionsResponse): + 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 = functions.ListFunctionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[functions.ListFunctionsResponse]: + 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[functions.Function]: + async def async_generator(): + async for page in self.pages: + for response in page.functions: + 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/functions_v2/services/function_service/transports/__init__.py b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/__init__.py new file mode 100644 index 0000000..5a68cc5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/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 FunctionServiceTransport +from .grpc import FunctionServiceGrpcTransport +from .grpc_asyncio import FunctionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FunctionServiceTransport]] +_transport_registry['grpc'] = FunctionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = FunctionServiceGrpcAsyncIOTransport + +__all__ = ( + 'FunctionServiceTransport', + 'FunctionServiceGrpcTransport', + 'FunctionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/base.py b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/base.py new file mode 100644 index 0000000..1c3faad --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/base.py @@ -0,0 +1,319 @@ +# -*- 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.functions_v2.types import functions +from google.cloud.location import locations_pb2 # type: ignore +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 +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-functions', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class FunctionServiceTransport(abc.ABC): + """Abstract transport class for FunctionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'cloudfunctions.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, + api_audience: Optional[str] = None, + **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. + """ + + 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) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_function: gapic_v1.method.wrap_method( + self.get_function, + default_timeout=None, + client_info=client_info, + ), + self.list_functions: gapic_v1.method.wrap_method( + self.list_functions, + default_timeout=None, + client_info=client_info, + ), + self.create_function: gapic_v1.method.wrap_method( + self.create_function, + default_timeout=None, + client_info=client_info, + ), + self.update_function: gapic_v1.method.wrap_method( + self.update_function, + default_timeout=None, + client_info=client_info, + ), + self.delete_function: gapic_v1.method.wrap_method( + self.delete_function, + default_timeout=None, + client_info=client_info, + ), + self.generate_upload_url: gapic_v1.method.wrap_method( + self.generate_upload_url, + default_timeout=None, + client_info=client_info, + ), + self.generate_download_url: gapic_v1.method.wrap_method( + self.generate_download_url, + default_timeout=None, + client_info=client_info, + ), + self.list_runtimes: gapic_v1.method.wrap_method( + self.list_runtimes, + 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_function(self) -> Callable[ + [functions.GetFunctionRequest], + Union[ + functions.Function, + Awaitable[functions.Function] + ]]: + raise NotImplementedError() + + @property + def list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + Union[ + functions.ListFunctionsResponse, + Awaitable[functions.ListFunctionsResponse] + ]]: + raise NotImplementedError() + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + Union[ + functions.GenerateUploadUrlResponse, + Awaitable[functions.GenerateUploadUrlResponse] + ]]: + raise NotImplementedError() + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Union[ + functions.GenerateDownloadUrlResponse, + Awaitable[functions.GenerateDownloadUrlResponse] + ]]: + raise NotImplementedError() + + @property + def list_runtimes(self) -> Callable[ + [functions.ListRuntimesRequest], + Union[ + functions.ListRuntimesResponse, + Awaitable[functions.ListRuntimesResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'FunctionServiceTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py new file mode 100644 index 0000000..46f5af8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py @@ -0,0 +1,645 @@ +# -*- 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.functions_v2.types import functions +from google.cloud.location import locations_pb2 # type: ignore +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 +from google.longrunning import operations_pb2 # type: ignore +from .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO + + +class FunctionServiceGrpcTransport(FunctionServiceTransport): + """gRPC backend transport for FunctionService. + + Google Cloud Functions is used to deploy functions that are executed + by Google in response to various events. Data connected with that + event is passed to a function as the input data. + + A **function** is a resource which describes a function that should + be executed and how it is triggered. + + 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 = 'cloudfunctions.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, + api_audience: Optional[str] = None, + ) -> 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, + api_audience=api_audience, + ) + + 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 = 'cloudfunctions.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_function(self) -> Callable[ + [functions.GetFunctionRequest], + functions.Function]: + r"""Return a callable for the get function method over gRPC. + + Returns a function with the given name from the + requested project. + + Returns: + Callable[[~.GetFunctionRequest], + ~.Function]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_function' not in self._stubs: + self._stubs['get_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/GetFunction', + request_serializer=functions.GetFunctionRequest.serialize, + response_deserializer=functions.Function.deserialize, + ) + return self._stubs['get_function'] + + @property + def list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + functions.ListFunctionsResponse]: + r"""Return a callable for the list functions method over gRPC. + + Returns a list of functions that belong to the + requested project. + + Returns: + Callable[[~.ListFunctionsRequest], + ~.ListFunctionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_functions' not in self._stubs: + self._stubs['list_functions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/ListFunctions', + request_serializer=functions.ListFunctionsRequest.serialize, + response_deserializer=functions.ListFunctionsResponse.deserialize, + ) + return self._stubs['list_functions'] + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create function method over gRPC. + + Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + Returns: + Callable[[~.CreateFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['create_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/CreateFunction', + request_serializer=functions.CreateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_function'] + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the update function method over gRPC. + + Updates existing function. + + Returns: + Callable[[~.UpdateFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['update_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/UpdateFunction', + request_serializer=functions.UpdateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_function'] + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete function method over gRPC. + + Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + Returns: + Callable[[~.DeleteFunctionRequest], + ~.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_function' not in self._stubs: + self._stubs['delete_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/DeleteFunction', + request_serializer=functions.DeleteFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_function'] + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + functions.GenerateUploadUrlResponse]: + r"""Return a callable for the generate upload url method over gRPC. + + Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + Returns: + Callable[[~.GenerateUploadUrlRequest], + ~.GenerateUploadUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_upload_url' not in self._stubs: + self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/GenerateUploadUrl', + request_serializer=functions.GenerateUploadUrlRequest.serialize, + response_deserializer=functions.GenerateUploadUrlResponse.deserialize, + ) + return self._stubs['generate_upload_url'] + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + functions.GenerateDownloadUrlResponse]: + r"""Return a callable for the generate download url method over gRPC. + + Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within 30 minutes of + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + Returns: + Callable[[~.GenerateDownloadUrlRequest], + ~.GenerateDownloadUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_download_url' not in self._stubs: + self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/GenerateDownloadUrl', + request_serializer=functions.GenerateDownloadUrlRequest.serialize, + response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, + ) + return self._stubs['generate_download_url'] + + @property + def list_runtimes(self) -> Callable[ + [functions.ListRuntimesRequest], + functions.ListRuntimesResponse]: + r"""Return a callable for the list runtimes method over gRPC. + + Returns a list of runtimes that are supported for the + requested project. + + Returns: + Callable[[~.ListRuntimesRequest], + ~.ListRuntimesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_runtimes' not in self._stubs: + self._stubs['list_runtimes'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/ListRuntimes', + request_serializer=functions.ListRuntimesRequest.serialize, + response_deserializer=functions.ListRuntimesResponse.deserialize, + ) + return self._stubs['list_runtimes'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'FunctionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..a9bd369 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py @@ -0,0 +1,644 @@ +# -*- 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.functions_v2.types import functions +from google.cloud.location import locations_pb2 # type: ignore +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 +from google.longrunning import operations_pb2 # type: ignore +from .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import FunctionServiceGrpcTransport + + +class FunctionServiceGrpcAsyncIOTransport(FunctionServiceTransport): + """gRPC AsyncIO backend transport for FunctionService. + + Google Cloud Functions is used to deploy functions that are executed + by Google in response to various events. Data connected with that + event is passed to a function as the input data. + + A **function** is a resource which describes a function that should + be executed and how it is triggered. + + 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 = 'cloudfunctions.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 = 'cloudfunctions.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, + api_audience: Optional[str] = None, + ) -> 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, + api_audience=api_audience, + ) + + 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_function(self) -> Callable[ + [functions.GetFunctionRequest], + Awaitable[functions.Function]]: + r"""Return a callable for the get function method over gRPC. + + Returns a function with the given name from the + requested project. + + Returns: + Callable[[~.GetFunctionRequest], + Awaitable[~.Function]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_function' not in self._stubs: + self._stubs['get_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/GetFunction', + request_serializer=functions.GetFunctionRequest.serialize, + response_deserializer=functions.Function.deserialize, + ) + return self._stubs['get_function'] + + @property + def list_functions(self) -> Callable[ + [functions.ListFunctionsRequest], + Awaitable[functions.ListFunctionsResponse]]: + r"""Return a callable for the list functions method over gRPC. + + Returns a list of functions that belong to the + requested project. + + Returns: + Callable[[~.ListFunctionsRequest], + Awaitable[~.ListFunctionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_functions' not in self._stubs: + self._stubs['list_functions'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/ListFunctions', + request_serializer=functions.ListFunctionsRequest.serialize, + response_deserializer=functions.ListFunctionsResponse.deserialize, + ) + return self._stubs['list_functions'] + + @property + def create_function(self) -> Callable[ + [functions.CreateFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create function method over gRPC. + + Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + Returns: + Callable[[~.CreateFunctionRequest], + 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_function' not in self._stubs: + self._stubs['create_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/CreateFunction', + request_serializer=functions.CreateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_function'] + + @property + def update_function(self) -> Callable[ + [functions.UpdateFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update function method over gRPC. + + Updates existing function. + + Returns: + Callable[[~.UpdateFunctionRequest], + 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_function' not in self._stubs: + self._stubs['update_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/UpdateFunction', + request_serializer=functions.UpdateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_function'] + + @property + def delete_function(self) -> Callable[ + [functions.DeleteFunctionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete function method over gRPC. + + Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + Returns: + Callable[[~.DeleteFunctionRequest], + 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_function' not in self._stubs: + self._stubs['delete_function'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/DeleteFunction', + request_serializer=functions.DeleteFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_function'] + + @property + def generate_upload_url(self) -> Callable[ + [functions.GenerateUploadUrlRequest], + Awaitable[functions.GenerateUploadUrlResponse]]: + r"""Return a callable for the generate upload url method over gRPC. + + Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + Returns: + Callable[[~.GenerateUploadUrlRequest], + Awaitable[~.GenerateUploadUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_upload_url' not in self._stubs: + self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/GenerateUploadUrl', + request_serializer=functions.GenerateUploadUrlRequest.serialize, + response_deserializer=functions.GenerateUploadUrlResponse.deserialize, + ) + return self._stubs['generate_upload_url'] + + @property + def generate_download_url(self) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Awaitable[functions.GenerateDownloadUrlResponse]]: + r"""Return a callable for the generate download url method over gRPC. + + Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within 30 minutes of + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + Returns: + Callable[[~.GenerateDownloadUrlRequest], + Awaitable[~.GenerateDownloadUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_download_url' not in self._stubs: + self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/GenerateDownloadUrl', + request_serializer=functions.GenerateDownloadUrlRequest.serialize, + response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, + ) + return self._stubs['generate_download_url'] + + @property + def list_runtimes(self) -> Callable[ + [functions.ListRuntimesRequest], + Awaitable[functions.ListRuntimesResponse]]: + r"""Return a callable for the list runtimes method over gRPC. + + Returns a list of runtimes that are supported for the + requested project. + + Returns: + Callable[[~.ListRuntimesRequest], + Awaitable[~.ListRuntimesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_runtimes' not in self._stubs: + self._stubs['list_runtimes'] = self.grpc_channel.unary_unary( + '/google.cloud.functions.v2.FunctionService/ListRuntimes', + request_serializer=functions.ListRuntimesRequest.serialize, + response_deserializer=functions.ListRuntimesResponse.deserialize, + ) + return self._stubs['list_runtimes'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'FunctionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/functions_v2/types/__init__.py new file mode 100644 index 0000000..33ebfca --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/types/__init__.py @@ -0,0 +1,74 @@ +# -*- 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 .functions import ( + BuildConfig, + CreateFunctionRequest, + DeleteFunctionRequest, + EventFilter, + EventTrigger, + Function, + GenerateDownloadUrlRequest, + GenerateDownloadUrlResponse, + GenerateUploadUrlRequest, + GenerateUploadUrlResponse, + GetFunctionRequest, + ListFunctionsRequest, + ListFunctionsResponse, + ListRuntimesRequest, + ListRuntimesResponse, + OperationMetadata, + RepoSource, + SecretEnvVar, + SecretVolume, + ServiceConfig, + Source, + SourceProvenance, + Stage, + StateMessage, + StorageSource, + UpdateFunctionRequest, + Environment, +) + +__all__ = ( + 'BuildConfig', + 'CreateFunctionRequest', + 'DeleteFunctionRequest', + 'EventFilter', + 'EventTrigger', + 'Function', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GetFunctionRequest', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'ListRuntimesRequest', + 'ListRuntimesResponse', + 'OperationMetadata', + 'RepoSource', + 'SecretEnvVar', + 'SecretVolume', + 'ServiceConfig', + 'Source', + 'SourceProvenance', + 'Stage', + 'StateMessage', + 'StorageSource', + 'UpdateFunctionRequest', + 'Environment', +) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/types/functions.py b/owl-bot-staging/v2/google/cloud/functions_v2/types/functions.py new file mode 100644 index 0000000..207cb88 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/functions_v2/types/functions.py @@ -0,0 +1,1363 @@ +# -*- 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 any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.functions.v2', + manifest={ + 'Environment', + 'Function', + 'StateMessage', + 'StorageSource', + 'RepoSource', + 'Source', + 'SourceProvenance', + 'BuildConfig', + 'ServiceConfig', + 'SecretEnvVar', + 'SecretVolume', + 'EventTrigger', + 'EventFilter', + 'GetFunctionRequest', + 'ListFunctionsRequest', + 'ListFunctionsResponse', + 'CreateFunctionRequest', + 'UpdateFunctionRequest', + 'DeleteFunctionRequest', + 'GenerateUploadUrlRequest', + 'GenerateUploadUrlResponse', + 'GenerateDownloadUrlRequest', + 'GenerateDownloadUrlResponse', + 'ListRuntimesRequest', + 'ListRuntimesResponse', + 'OperationMetadata', + 'Stage', + }, +) + + +class Environment(proto.Enum): + r"""The environment the function is hosted on.""" + ENVIRONMENT_UNSPECIFIED = 0 + GEN_1 = 1 + GEN_2 = 2 + + +class Function(proto.Message): + r"""Describes a Cloud Function that contains user computation + executed in response to an event. It encapsulates function and + trigger configurations. + + Attributes: + name (str): + A user-defined name of the function. Function names must be + unique globally and match pattern + ``projects/*/locations/*/functions/*`` + environment (google.cloud.functions_v2.types.Environment): + Describe whether the function is gen1 or + gen2. + description (str): + User-provided description of a function. + build_config (google.cloud.functions_v2.types.BuildConfig): + Describes the Build step of the function that + builds a container from the given source. + service_config (google.cloud.functions_v2.types.ServiceConfig): + Describes the Service being deployed. + Currently deploys services to Cloud Run (fully + managed). + event_trigger (google.cloud.functions_v2.types.EventTrigger): + An Eventarc trigger managed by Google Cloud + Functions that fires events in response to a + condition in another service. + state (google.cloud.functions_v2.types.Function.State): + Output only. State of the function. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update timestamp of a + Cloud Function. + labels (Mapping[str, str]): + Labels associated with this Cloud Function. + state_messages (Sequence[google.cloud.functions_v2.types.StateMessage]): + Output only. State Messages for this Cloud + Function. + """ + class State(proto.Enum): + r"""Describes the current state of the function.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + FAILED = 2 + DEPLOYING = 3 + DELETING = 4 + UNKNOWN = 5 + + name = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.ENUM, + number=10, + enum='Environment', + ) + description = proto.Field( + proto.STRING, + number=2, + ) + build_config = proto.Field( + proto.MESSAGE, + number=3, + message='BuildConfig', + ) + service_config = proto.Field( + proto.MESSAGE, + number=4, + message='ServiceConfig', + ) + event_trigger = proto.Field( + proto.MESSAGE, + number=5, + message='EventTrigger', + ) + state = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + update_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + state_messages = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='StateMessage', + ) + + +class StateMessage(proto.Message): + r"""Informational messages about the state of the Cloud Function + or Operation. + + Attributes: + severity (google.cloud.functions_v2.types.StateMessage.Severity): + Severity of the state message. + type_ (str): + One-word CamelCase type of the state message. + message (str): + The message. + """ + class Severity(proto.Enum): + r"""Severity of the state message.""" + SEVERITY_UNSPECIFIED = 0 + ERROR = 1 + WARNING = 2 + INFO = 3 + + severity = proto.Field( + proto.ENUM, + number=1, + enum=Severity, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + message = proto.Field( + proto.STRING, + number=3, + ) + + +class StorageSource(proto.Message): + r"""Location of the source in an archive file in Google Cloud + Storage. + + Attributes: + bucket (str): + Google Cloud Storage bucket containing the source (see + `Bucket Name + Requirements `__). + object_ (str): + Google Cloud Storage object containing the source. + + This object must be a gzipped archive file (``.tar.gz``) + containing source to build. + generation (int): + Google Cloud Storage generation for the + object. If the generation is omitted, the latest + generation will be used. + """ + + bucket = proto.Field( + proto.STRING, + number=1, + ) + object_ = proto.Field( + proto.STRING, + number=2, + ) + generation = proto.Field( + proto.INT64, + number=3, + ) + + +class RepoSource(proto.Message): + r"""Location of the source in a Google Cloud Source Repository. + + 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: + branch_name (str): + Regex matching branches to build. + The syntax of the regular expressions accepted + is the syntax accepted by RE2 and described at + https://github.com/google/re2/wiki/Syntax + + This field is a member of `oneof`_ ``revision``. + tag_name (str): + Regex matching tags to build. + The syntax of the regular expressions accepted + is the syntax accepted by RE2 and described at + https://github.com/google/re2/wiki/Syntax + + This field is a member of `oneof`_ ``revision``. + commit_sha (str): + Explicit commit SHA to build. + + This field is a member of `oneof`_ ``revision``. + project_id (str): + ID of the project that owns the Cloud Source + Repository. If omitted, the project ID + requesting the build is assumed. + repo_name (str): + Name of the Cloud Source Repository. + dir_ (str): + Directory, relative to the source root, in which to run the + build. + + This must be a relative path. If a step's ``dir`` is + specified and is an absolute path, this value is ignored for + that step's execution. eg. helloworld (no leading slash + allowed) + invert_regex (bool): + Only trigger a build if the revision regex + does NOT match the revision regex. + """ + + branch_name = proto.Field( + proto.STRING, + number=3, + oneof='revision', + ) + tag_name = proto.Field( + proto.STRING, + number=4, + oneof='revision', + ) + commit_sha = proto.Field( + proto.STRING, + number=5, + oneof='revision', + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + repo_name = proto.Field( + proto.STRING, + number=2, + ) + dir_ = proto.Field( + proto.STRING, + number=6, + ) + invert_regex = proto.Field( + proto.BOOL, + number=7, + ) + + +class Source(proto.Message): + r"""The location of the function source code. + + 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: + storage_source (google.cloud.functions_v2.types.StorageSource): + If provided, get the source from this + location in Google Cloud Storage. + + This field is a member of `oneof`_ ``source``. + repo_source (google.cloud.functions_v2.types.RepoSource): + If provided, get the source from this + location in a Cloud Source Repository. + + This field is a member of `oneof`_ ``source``. + """ + + storage_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='StorageSource', + ) + repo_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='RepoSource', + ) + + +class SourceProvenance(proto.Message): + r"""Provenance of the source. Ways to find the original source, + or verify that some source was used for this build. + + Attributes: + resolved_storage_source (google.cloud.functions_v2.types.StorageSource): + A copy of the build's ``source.storage_source``, if exists, + with any generations resolved. + resolved_repo_source (google.cloud.functions_v2.types.RepoSource): + A copy of the build's ``source.repo_source``, if exists, + with any revisions resolved. + """ + + resolved_storage_source = proto.Field( + proto.MESSAGE, + number=1, + message='StorageSource', + ) + resolved_repo_source = proto.Field( + proto.MESSAGE, + number=2, + message='RepoSource', + ) + + +class BuildConfig(proto.Message): + r"""Describes the Build step of the function that builds a + container from the given source. + + Attributes: + build (str): + Output only. The Cloud Build name of the + latest successful deployment of the function. + runtime (str): + The runtime in which to run the function. Required when + deploying a new function, optional when updating an existing + function. For a complete list of possible choices, see the + ```gcloud`` command + reference `__. + entry_point (str): + The name of the function (as defined in source code) that + will be executed. Defaults to the resource name suffix, if + not specified. For backward compatibility, if function with + given name is not found, then the system will try to use + function named "function". For Node.js this is name of a + function exported by the module specified in + ``source_location``. + source (google.cloud.functions_v2.types.Source): + The location of the function source code. + source_provenance (google.cloud.functions_v2.types.SourceProvenance): + Output only. A permanent fixed identifier for + source. + worker_pool (str): + Name of the Cloud Build Custom Worker Pool that should be + used to build the function. The format of this field is + ``projects/{project}/locations/{region}/workerPools/{workerPool}`` + where {project} and {region} are the project id and region + respectively where the worker pool is defined and + {workerPool} is the short name of the worker pool. + + If the project id is not the same as the function, then the + Cloud Functions Service Agent + (service-@gcf-admin-robot.iam.gserviceaccount.com) + must be granted the role Cloud Build Custom Workers Builder + (roles/cloudbuild.customworkers.builder) in the project. + environment_variables (Mapping[str, str]): + User-provided build-time environment + variables for the function + docker_repository (str): + Optional. User managed repository created in Artifact + Registry optionally with a customer managed encryption key. + This is the repository to which the function docker image + will be pushed after it is built by Cloud Build. If + unspecified, GCF will create and use a repository named + 'gcf-artifacts' for every deployed region. + + It must match the pattern + ``projects/{project}/locations/{location}/repositories/{repository}``. + + Cross-project repositories are not supported. Cross-location + repositories are not supported. Repository format must be + 'DOCKER'. + """ + + build = proto.Field( + proto.STRING, + number=1, + ) + runtime = proto.Field( + proto.STRING, + number=2, + ) + entry_point = proto.Field( + proto.STRING, + number=3, + ) + source = proto.Field( + proto.MESSAGE, + number=4, + message='Source', + ) + source_provenance = proto.Field( + proto.MESSAGE, + number=8, + message='SourceProvenance', + ) + worker_pool = proto.Field( + proto.STRING, + number=5, + ) + environment_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + docker_repository = proto.Field( + proto.STRING, + number=7, + ) + + +class ServiceConfig(proto.Message): + r"""Describes the Service being deployed. + Currently Supported : Cloud Run (fully managed). + + Attributes: + service (str): + Output only. Name of the service associated with a Function. + The format of this field is + ``projects/{project}/locations/{region}/services/{service}`` + timeout_seconds (int): + The function execution timeout. Execution is + considered failed and can be terminated if the + function is not completed at the end of the + timeout period. Defaults to 60 seconds. + available_memory (str): + The amount of memory available for a + function. Defaults to 256M. Supported units are + k, M, G, Mi, Gi. If no unit is supplied the + value is interpreted as bytes. + See + https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go + a full description. + environment_variables (Mapping[str, str]): + Environment variables that shall be available + during function execution. + max_instance_count (int): + The limit on the maximum number of function instances that + may coexist at a given time. + + In some cases, such as rapid traffic surges, Cloud Functions + may, for a short period of time, create more instances than + the specified max instances limit. If your function cannot + tolerate this temporary behavior, you may want to factor in + a safety margin and set a lower max instances value than + your function can tolerate. + + See the `Max + Instances `__ + Guide for more details. + min_instance_count (int): + The limit on the minimum number of function + instances that may coexist at a given time. + + Function instances are kept in idle state for a + short period after they finished executing the + request to reduce cold start time for subsequent + requests. Setting a minimum instance count will + ensure that the given number of instances are + kept running in idle state always. This can help + with cold start times when jump in incoming + request count occurs after the idle instance + would have been stopped in the default case. + vpc_connector (str): + The Serverless VPC Access connector that this cloud function + can connect to. The format of this field is + ``projects/*/locations/*/connectors/*``. + vpc_connector_egress_settings (google.cloud.functions_v2.types.ServiceConfig.VpcConnectorEgressSettings): + The egress settings for the connector, + controlling what traffic is diverted through it. + ingress_settings (google.cloud.functions_v2.types.ServiceConfig.IngressSettings): + The ingress settings for the function, + controlling what traffic can reach it. + uri (str): + Output only. URI of the Service deployed. + service_account_email (str): + The email of the service's service account. If empty, + defaults to + ``{project_number}-compute@developer.gserviceaccount.com``. + all_traffic_on_latest_revision (bool): + Whether 100% of traffic is routed to the + latest revision. On CreateFunction and + UpdateFunction, when set to true, the revision + being deployed will serve 100% of traffic, + ignoring any traffic split settings, if any. On + GetFunction, true will be returned if the latest + revision is serving 100% of traffic. + secret_environment_variables (Sequence[google.cloud.functions_v2.types.SecretEnvVar]): + Secret environment variables configuration. + secret_volumes (Sequence[google.cloud.functions_v2.types.SecretVolume]): + Secret volumes configuration. + revision (str): + Output only. The name of service revision. + """ + class VpcConnectorEgressSettings(proto.Enum): + r"""Available egress settings. + + This controls what traffic is diverted through the VPC Access + Connector resource. By default PRIVATE_RANGES_ONLY will be used. + """ + VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED = 0 + PRIVATE_RANGES_ONLY = 1 + ALL_TRAFFIC = 2 + + class IngressSettings(proto.Enum): + r"""Available ingress settings. + + This controls what traffic can reach the function. + + If unspecified, ALLOW_ALL will be used. + """ + INGRESS_SETTINGS_UNSPECIFIED = 0 + ALLOW_ALL = 1 + ALLOW_INTERNAL_ONLY = 2 + ALLOW_INTERNAL_AND_GCLB = 3 + + service = proto.Field( + proto.STRING, + number=1, + ) + timeout_seconds = proto.Field( + proto.INT32, + number=2, + ) + available_memory = proto.Field( + proto.STRING, + number=13, + ) + environment_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + max_instance_count = proto.Field( + proto.INT32, + number=5, + ) + min_instance_count = proto.Field( + proto.INT32, + number=12, + ) + vpc_connector = proto.Field( + proto.STRING, + number=6, + ) + vpc_connector_egress_settings = proto.Field( + proto.ENUM, + number=7, + enum=VpcConnectorEgressSettings, + ) + ingress_settings = proto.Field( + proto.ENUM, + number=8, + enum=IngressSettings, + ) + uri = proto.Field( + proto.STRING, + number=9, + ) + service_account_email = proto.Field( + proto.STRING, + number=10, + ) + all_traffic_on_latest_revision = proto.Field( + proto.BOOL, + number=16, + ) + secret_environment_variables = proto.RepeatedField( + proto.MESSAGE, + number=17, + message='SecretEnvVar', + ) + secret_volumes = proto.RepeatedField( + proto.MESSAGE, + number=19, + message='SecretVolume', + ) + revision = proto.Field( + proto.STRING, + number=18, + ) + + +class SecretEnvVar(proto.Message): + r"""Configuration for a secret environment variable. It has the + information necessary to fetch the secret value from secret + manager and expose it as an environment variable. + + Attributes: + key (str): + Name of the environment variable. + project_id (str): + Project identifier (preferably project number + but can also be the project ID) of the project + that contains the secret. If not set, it is + assumed that the secret is in the same project + as the function. + secret (str): + Name of the secret in secret manager (not the + full resource name). + version (str): + Version of the secret (version number or the + string 'latest'). It is recommended to use a + numeric version for secret environment variables + as any updates to the secret value is not + reflected until new instances start. + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + secret = proto.Field( + proto.STRING, + number=3, + ) + version = proto.Field( + proto.STRING, + number=4, + ) + + +class SecretVolume(proto.Message): + r"""Configuration for a secret volume. It has the information + necessary to fetch the secret value from secret manager and make + it available as files mounted at the requested paths within the + application container. + + Attributes: + mount_path (str): + The path within the container to mount the secret volume. + For example, setting the mount_path as ``/etc/secrets`` + would mount the secret value files under the + ``/etc/secrets`` directory. This directory will also be + completely shadowed and unavailable to mount any other + secrets. Recommended mount path: /etc/secrets + project_id (str): + Project identifier (preferably project number + but can also be the project ID) of the project + that contains the secret. If not set, it is + assumed that the secret is in the same project + as the function. + secret (str): + Name of the secret in secret manager (not the + full resource name). + versions (Sequence[google.cloud.functions_v2.types.SecretVolume.SecretVersion]): + List of secret versions to mount for this secret. If empty, + the ``latest`` version of the secret will be made available + in a file named after the secret under the mount point. + """ + + class SecretVersion(proto.Message): + r"""Configuration for a single version. + + Attributes: + version (str): + Version of the secret (version number or the string + 'latest'). It is preferable to use ``latest`` version with + secret volumes as secret value changes are reflected + immediately. + path (str): + Relative path of the file under the mount path where the + secret value for this version will be fetched and made + available. For example, setting the mount_path as + '/etc/secrets' and path as ``secret_foo`` would mount the + secret value file at ``/etc/secrets/secret_foo``. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + path = proto.Field( + proto.STRING, + number=2, + ) + + mount_path = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + secret = proto.Field( + proto.STRING, + number=3, + ) + versions = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=SecretVersion, + ) + + +class EventTrigger(proto.Message): + r"""Describes EventTrigger, used to request events to be sent + from another service. + + Attributes: + trigger (str): + Output only. The resource name of the Eventarc trigger. The + format of this field is + ``projects/{project}/locations/{region}/triggers/{trigger}``. + trigger_region (str): + The region that the trigger will be in. The + trigger will only receive events originating in + this region. It can be the same region as the + function, a different region or multi-region, or + the global region. If not provided, defaults to + the same region as the function. + event_type (str): + Required. The type of event to observe. For example: + ``google.cloud.audit.log.v1.written`` or + ``google.cloud.pubsub.topic.v1.messagePublished``. + event_filters (Sequence[google.cloud.functions_v2.types.EventFilter]): + Criteria used to filter events. + pubsub_topic (str): + Optional. The name of a Pub/Sub topic in the same project + that will be used as the transport topic for the event + delivery. Format: ``projects/{project}/topics/{topic}``. + + This is only valid for events of type + ``google.cloud.pubsub.topic.v1.messagePublished``. The topic + provided here will not be deleted at function deletion. + service_account_email (str): + Optional. The email of the trigger's service account. The + service account must have permission to invoke Cloud Run + services, the permission is ``run.routes.invoke``. If empty, + defaults to the Compute Engine default service account: + ``{project_number}-compute@developer.gserviceaccount.com``. + retry_policy (google.cloud.functions_v2.types.EventTrigger.RetryPolicy): + Optional. If unset, then defaults to ignoring + failures (i.e. not retrying them). + channel (str): + Optional. The name of the channel associated with the + trigger in + ``projects/{project}/locations/{location}/channels/{channel}`` + format. You must provide a channel to receive events from + Eventarc SaaS partners. + """ + class RetryPolicy(proto.Enum): + r"""Describes the retry policy in case of function's execution + failure. Retried execution is charged as any other execution. + """ + RETRY_POLICY_UNSPECIFIED = 0 + RETRY_POLICY_DO_NOT_RETRY = 1 + RETRY_POLICY_RETRY = 2 + + trigger = proto.Field( + proto.STRING, + number=1, + ) + trigger_region = proto.Field( + proto.STRING, + number=2, + ) + event_type = proto.Field( + proto.STRING, + number=3, + ) + event_filters = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='EventFilter', + ) + pubsub_topic = proto.Field( + proto.STRING, + number=5, + ) + service_account_email = proto.Field( + proto.STRING, + number=6, + ) + retry_policy = proto.Field( + proto.ENUM, + number=7, + enum=RetryPolicy, + ) + channel = proto.Field( + proto.STRING, + number=8, + ) + + +class EventFilter(proto.Message): + r"""Filters events based on exact matches on the CloudEvents + attributes. + + Attributes: + attribute (str): + Required. The name of a CloudEvents + attribute. + value (str): + Required. The value for the attribute. + operator (str): + Optional. The operator used for matching the events with the + value of the filter. If not specified, only events that have + an exact key-value pair specified in the filter are matched. + The only allowed value is ``match-path-pattern``. + """ + + attribute = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.STRING, + number=2, + ) + operator = proto.Field( + proto.STRING, + number=3, + ) + + +class GetFunctionRequest(proto.Message): + r"""Request for the ``GetFunction`` method. + + Attributes: + name (str): + Required. The name of the function which + details should be obtained. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFunctionsRequest(proto.Message): + r"""Request for the ``ListFunctions`` method. + + Attributes: + parent (str): + Required. The project and location from which the function + should be listed, specified in the format + ``projects/*/locations/*`` If you want to list functions in + all locations, use "-" in place of a location. When listing + functions in all locations, if one or more location(s) are + unreachable, the response will contain functions from all + reachable locations along with the names of any unreachable + locations. + page_size (int): + Maximum number of functions to return per + call. + page_token (str): + The value returned by the last ``ListFunctionsResponse``; + indicates that this is a continuation of a prior + ``ListFunctions`` call, and that the system should return + the next page of data. + filter (str): + The filter for Functions that match the + filter expression, following the syntax outlined + in https://google.aip.dev/160. + order_by (str): + The sorting order of the resources returned. + Value should be a comma separated list of + fields. The default sorting oder is ascending. + See https://google.aip.dev/132#ordering. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class ListFunctionsResponse(proto.Message): + r"""Response for the ``ListFunctions`` method. + + Attributes: + functions (Sequence[google.cloud.functions_v2.types.Function]): + The functions that match the request. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (Sequence[str]): + Locations that could not be reached. The + response does not include any functions from + these locations. + """ + + @property + def raw_page(self): + return self + + functions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Function', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + unreachable = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateFunctionRequest(proto.Message): + r"""Request for the ``CreateFunction`` method. + + Attributes: + parent (str): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + function (google.cloud.functions_v2.types.Function): + Required. Function to be created. + function_id (str): + The ID to use for the function, which will become the final + component of the function's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + function = proto.Field( + proto.MESSAGE, + number=2, + message='Function', + ) + function_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateFunctionRequest(proto.Message): + r"""Request for the ``UpdateFunction`` method. + + Attributes: + function (google.cloud.functions_v2.types.Function): + Required. New version of the function. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If no field mask is provided, all provided + fields in the request will be updated. + """ + + function = proto.Field( + proto.MESSAGE, + number=1, + message='Function', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteFunctionRequest(proto.Message): + r"""Request for the ``DeleteFunction`` method. + + Attributes: + name (str): + Required. The name of the function which + should be deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateUploadUrlRequest(proto.Message): + r"""Request of ``GenerateSourceUploadUrl`` method. + + Attributes: + parent (str): + Required. The project and location in which the Google Cloud + Storage signed URL should be generated, specified in the + format ``projects/*/locations/*``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateUploadUrlResponse(proto.Message): + r"""Response of ``GenerateSourceUploadUrl`` method. + + Attributes: + upload_url (str): + The generated Google Cloud Storage signed URL + that should be used for a function source code + upload. The uploaded file should be a zip + archive which contains a function. + storage_source (google.cloud.functions_v2.types.StorageSource): + The location of the source code in the upload bucket. + + Once the archive is uploaded using the ``upload_url`` use + this field to set the + ``function.build_config.source.storage_source`` during + CreateFunction and UpdateFunction. + + Generation defaults to 0, as Cloud Storage provides a new + generation only upon uploading a new object or version of an + object. + """ + + upload_url = proto.Field( + proto.STRING, + number=1, + ) + storage_source = proto.Field( + proto.MESSAGE, + number=2, + message='StorageSource', + ) + + +class GenerateDownloadUrlRequest(proto.Message): + r"""Request of ``GenerateDownloadUrl`` method. + + Attributes: + name (str): + Required. The name of function for which + source code Google Cloud Storage signed URL + should be generated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateDownloadUrlResponse(proto.Message): + r"""Response of ``GenerateDownloadUrl`` method. + + Attributes: + download_url (str): + The generated Google Cloud Storage signed URL + that should be used for function source code + download. + """ + + download_url = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRuntimesRequest(proto.Message): + r"""Request for the ``ListRuntimes`` method. + + Attributes: + parent (str): + Required. The project and location from which the runtimes + should be listed, specified in the format + ``projects/*/locations/*`` + filter (str): + The filter for Runtimes that match the filter + expression, following the syntax outlined in + https://google.aip.dev/160. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + + +class ListRuntimesResponse(proto.Message): + r"""Response for the ``ListRuntimes`` method. + + Attributes: + runtimes (Sequence[google.cloud.functions_v2.types.ListRuntimesResponse.Runtime]): + The runtimes that match the request. + """ + class RuntimeStage(proto.Enum): + r"""The various stages that a runtime can be in.""" + RUNTIME_STAGE_UNSPECIFIED = 0 + DEVELOPMENT = 1 + ALPHA = 2 + BETA = 3 + GA = 4 + DEPRECATED = 5 + DECOMMISSIONED = 6 + + class Runtime(proto.Message): + r"""Describes a runtime and any special information (e.g., + deprecation status) related to it. + + Attributes: + name (str): + The name of the runtime, e.g., 'go113', + 'nodejs12', etc. + display_name (str): + The user facing name, eg 'Go 1.13', 'Node.js + 12', etc. + stage (google.cloud.functions_v2.types.ListRuntimesResponse.RuntimeStage): + The stage of life this runtime is in, e.g., + BETA, GA, etc. + warnings (Sequence[str]): + Warning messages, e.g., a deprecation + warning. + environment (google.cloud.functions_v2.types.Environment): + The environment for the runtime. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=5, + ) + stage = proto.Field( + proto.ENUM, + number=2, + enum='ListRuntimesResponse.RuntimeStage', + ) + warnings = proto.RepeatedField( + proto.STRING, + number=3, + ) + environment = proto.Field( + proto.ENUM, + number=4, + enum='Environment', + ) + + runtimes = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Runtime, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation was created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation finished running. + target (str): + Server-defined resource path for the target + of the operation. + verb (str): + Name of the verb executed by the operation. + status_detail (str): + Human-readable status of the operation, if + any. + cancel_requested (bool): + Identifies whether the user has requested cancellation of + the operation. Operations that have successfully been + cancelled have [Operation.error][] value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. + api_version (str): + API version used to start the operation. + request_resource (google.protobuf.any_pb2.Any): + The original request that started the + operation. + stages (Sequence[google.cloud.functions_v2.types.Stage]): + Mechanism for reporting in-progress stages + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target = proto.Field( + proto.STRING, + number=3, + ) + verb = proto.Field( + proto.STRING, + number=4, + ) + status_detail = proto.Field( + proto.STRING, + number=5, + ) + cancel_requested = proto.Field( + proto.BOOL, + number=6, + ) + api_version = proto.Field( + proto.STRING, + number=7, + ) + request_resource = proto.Field( + proto.MESSAGE, + number=8, + message=any_pb2.Any, + ) + stages = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='Stage', + ) + + +class Stage(proto.Message): + r"""Each Stage of the deployment process + + Attributes: + name (google.cloud.functions_v2.types.Stage.Name): + Name of the Stage. This will be unique for + each Stage. + message (str): + Message describing the Stage + state (google.cloud.functions_v2.types.Stage.State): + Current state of the Stage + resource (str): + Resource of the Stage + resource_uri (str): + Link to the current Stage resource + state_messages (Sequence[google.cloud.functions_v2.types.StateMessage]): + State messages from the current Stage. + """ + class Name(proto.Enum): + r"""Possible names for a Stage""" + NAME_UNSPECIFIED = 0 + ARTIFACT_REGISTRY = 1 + BUILD = 2 + SERVICE = 3 + TRIGGER = 4 + SERVICE_ROLLBACK = 5 + TRIGGER_ROLLBACK = 6 + + class State(proto.Enum): + r"""Possible states for a Stage""" + STATE_UNSPECIFIED = 0 + NOT_STARTED = 1 + IN_PROGRESS = 2 + COMPLETE = 3 + + name = proto.Field( + proto.ENUM, + number=1, + enum=Name, + ) + message = proto.Field( + proto.STRING, + number=2, + ) + state = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + resource = proto.Field( + proto.STRING, + number=4, + ) + resource_uri = proto.Field( + proto.STRING, + number=5, + ) + state_messages = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='StateMessage', + ) + + +__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..5dcdf9d --- /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', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/functions_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/cloudfunctions_v2_generated_function_service_create_function_async.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py new file mode 100644 index 0000000..b0a73a3 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_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 CreateFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_CreateFunction_async] +from google.cloud import functions_v2 + + +async def sample_create_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.CreateFunctionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_CreateFunction_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py new file mode 100644 index 0000000..5f0ffb7 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_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 CreateFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_CreateFunction_sync] +from google.cloud import functions_v2 + + +def sample_create_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.CreateFunctionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_CreateFunction_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py new file mode 100644 index 0000000..75bd16c --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_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 DeleteFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_DeleteFunction_async] +from google.cloud import functions_v2 + + +async def sample_delete_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_DeleteFunction_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py new file mode 100644 index 0000000..5ecc4f6 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_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 DeleteFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_DeleteFunction_sync] +from google.cloud import functions_v2 + + +def sample_delete_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_DeleteFunction_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py new file mode 100644 index 0000000..de16eda --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_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 GenerateDownloadUrl +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_async] +from google.cloud import functions_v2 + + +async def sample_generate_download_url(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GenerateDownloadUrlRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_download_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py new file mode 100644 index 0000000..c00c0c4 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_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 GenerateDownloadUrl +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_sync] +from google.cloud import functions_v2 + + +def sample_generate_download_url(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GenerateDownloadUrlRequest( + name="name_value", + ) + + # Make the request + response = client.generate_download_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py new file mode 100644 index 0000000..c66940c --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_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 GenerateUploadUrl +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_async] +from google.cloud import functions_v2 + + +async def sample_generate_upload_url(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GenerateUploadUrlRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_upload_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py new file mode 100644 index 0000000..f895b86 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_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 GenerateUploadUrl +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_sync] +from google.cloud import functions_v2 + + +def sample_generate_upload_url(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GenerateUploadUrlRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_upload_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py new file mode 100644 index 0000000..43d5dfb --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_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 GetFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GetFunction_async] +from google.cloud import functions_v2 + + +async def sample_get_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GetFunction_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py new file mode 100644 index 0000000..8bb3cfa --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_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 GetFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GetFunction_sync] +from google.cloud import functions_v2 + + +def sample_get_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = client.get_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GetFunction_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py new file mode 100644 index 0000000..50b0e79 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_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 ListFunctions +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_ListFunctions_async] +from google.cloud import functions_v2 + + +async def sample_list_functions(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.ListFunctionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_ListFunctions_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py new file mode 100644 index 0000000..33ae5c5 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_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 ListFunctions +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_ListFunctions_sync] +from google.cloud import functions_v2 + + +def sample_list_functions(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.ListFunctionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_ListFunctions_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py new file mode 100644 index 0000000..410226f --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_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 ListRuntimes +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_ListRuntimes_async] +from google.cloud import functions_v2 + + +async def sample_list_runtimes(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.ListRuntimesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_runtimes(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_ListRuntimes_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py new file mode 100644 index 0000000..b942e09 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_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 ListRuntimes +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_ListRuntimes_sync] +from google.cloud import functions_v2 + + +def sample_list_runtimes(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.ListRuntimesRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_runtimes(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_ListRuntimes_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py new file mode 100644 index 0000000..42fc516 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_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 UpdateFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_UpdateFunction_async] +from google.cloud import functions_v2 + + +async def sample_update_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.UpdateFunctionRequest( + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_UpdateFunction_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py new file mode 100644 index 0000000..dfb7969 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_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 UpdateFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_UpdateFunction_sync] +from google.cloud import functions_v2 + + +def sample_update_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.UpdateFunctionRequest( + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_UpdateFunction_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_functions_v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_functions_v2.json new file mode 100644 index 0000000..7b0dbb7 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_functions_v2.json @@ -0,0 +1,1310 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.functions.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-cloud-functions" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.create_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.CreateFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "CreateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.CreateFunctionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "function", + "type": "google.cloud.functions_v2.types.Function" + }, + { + "name": "function_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_function" + }, + "description": "Sample for CreateFunction", + "file": "cloudfunctions_v2_generated_function_service_create_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_CreateFunction_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_create_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.create_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.CreateFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "CreateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.CreateFunctionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "function", + "type": "google.cloud.functions_v2.types.Function" + }, + { + "name": "function_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_function" + }, + "description": "Sample for CreateFunction", + "file": "cloudfunctions_v2_generated_function_service_create_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_CreateFunction_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_create_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.delete_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.DeleteFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "DeleteFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.DeleteFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_function" + }, + "description": "Sample for DeleteFunction", + "file": "cloudfunctions_v2_generated_function_service_delete_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_DeleteFunction_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_delete_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.delete_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.DeleteFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "DeleteFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.DeleteFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_function" + }, + "description": "Sample for DeleteFunction", + "file": "cloudfunctions_v2_generated_function_service_delete_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_DeleteFunction_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_delete_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.generate_download_url", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GenerateDownloadUrl", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GenerateDownloadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GenerateDownloadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.GenerateDownloadUrlResponse", + "shortName": "generate_download_url" + }, + "description": "Sample for GenerateDownloadUrl", + "file": "cloudfunctions_v2_generated_function_service_generate_download_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_generate_download_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.generate_download_url", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GenerateDownloadUrl", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GenerateDownloadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GenerateDownloadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.GenerateDownloadUrlResponse", + "shortName": "generate_download_url" + }, + "description": "Sample for GenerateDownloadUrl", + "file": "cloudfunctions_v2_generated_function_service_generate_download_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_generate_download_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.generate_upload_url", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GenerateUploadUrl", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GenerateUploadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GenerateUploadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.GenerateUploadUrlResponse", + "shortName": "generate_upload_url" + }, + "description": "Sample for GenerateUploadUrl", + "file": "cloudfunctions_v2_generated_function_service_generate_upload_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_generate_upload_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.generate_upload_url", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GenerateUploadUrl", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GenerateUploadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GenerateUploadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.GenerateUploadUrlResponse", + "shortName": "generate_upload_url" + }, + "description": "Sample for GenerateUploadUrl", + "file": "cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.get_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GetFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GetFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GetFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.Function", + "shortName": "get_function" + }, + "description": "Sample for GetFunction", + "file": "cloudfunctions_v2_generated_function_service_get_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GetFunction_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_get_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.get_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GetFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GetFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GetFunctionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.Function", + "shortName": "get_function" + }, + "description": "Sample for GetFunction", + "file": "cloudfunctions_v2_generated_function_service_get_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GetFunction_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_get_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.list_functions", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.ListFunctions", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "ListFunctions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.ListFunctionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.services.function_service.pagers.ListFunctionsAsyncPager", + "shortName": "list_functions" + }, + "description": "Sample for ListFunctions", + "file": "cloudfunctions_v2_generated_function_service_list_functions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_ListFunctions_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_list_functions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.list_functions", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.ListFunctions", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "ListFunctions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.ListFunctionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.services.function_service.pagers.ListFunctionsPager", + "shortName": "list_functions" + }, + "description": "Sample for ListFunctions", + "file": "cloudfunctions_v2_generated_function_service_list_functions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_ListFunctions_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_list_functions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.list_runtimes", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.ListRuntimes", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "ListRuntimes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.ListRuntimesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.ListRuntimesResponse", + "shortName": "list_runtimes" + }, + "description": "Sample for ListRuntimes", + "file": "cloudfunctions_v2_generated_function_service_list_runtimes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_ListRuntimes_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_list_runtimes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.list_runtimes", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.ListRuntimes", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "ListRuntimes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.ListRuntimesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.ListRuntimesResponse", + "shortName": "list_runtimes" + }, + "description": "Sample for ListRuntimes", + "file": "cloudfunctions_v2_generated_function_service_list_runtimes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_ListRuntimes_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_list_runtimes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.update_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.UpdateFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "UpdateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.UpdateFunctionRequest" + }, + { + "name": "function", + "type": "google.cloud.functions_v2.types.Function" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_function" + }, + "description": "Sample for UpdateFunction", + "file": "cloudfunctions_v2_generated_function_service_update_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_UpdateFunction_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_update_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.update_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.UpdateFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "UpdateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.UpdateFunctionRequest" + }, + { + "name": "function", + "type": "google.cloud.functions_v2.types.Function" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_function" + }, + "description": "Sample for UpdateFunction", + "file": "cloudfunctions_v2_generated_function_service_update_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_UpdateFunction_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" + } + ], + "title": "cloudfunctions_v2_generated_function_service_update_function_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2/scripts/fixup_functions_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_functions_v2_keywords.py new file mode 100644 index 0000000..e957319 --- /dev/null +++ b/owl-bot-staging/v2/scripts/fixup_functions_v2_keywords.py @@ -0,0 +1,183 @@ +#! /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 functionsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_function': ('parent', 'function', 'function_id', ), + 'delete_function': ('name', ), + 'generate_download_url': ('name', ), + 'generate_upload_url': ('parent', ), + 'get_function': ('name', ), + 'list_functions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_runtimes': ('parent', 'filter', ), + 'update_function': ('function', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=functionsCallTransformer(), +): + """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 functions 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..820b19a --- /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-functions', + author="Google LLC", + author_email="googleapis-packages@google.com", + url="https://github.com/googleapis/python-google-cloud-functions", + 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] >= 2.8.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.4, < 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/functions_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/functions_v2/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/functions_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/functions_v2/test_function_service.py b/owl-bot-staging/v2/tests/unit/gapic/functions_v2/test_function_service.py new file mode 100644 index 0000000..724b533 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/functions_v2/test_function_service.py @@ -0,0 +1,4158 @@ +# -*- 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 +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock +except ImportError: + import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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.functions_v2.services.function_service import FunctionServiceAsyncClient +from google.cloud.functions_v2.services.function_service import FunctionServiceClient +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.services.function_service import transports +from google.cloud.functions_v2.types import functions +from google.cloud.location import locations_pb2 +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 field_mask_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 FunctionServiceClient._get_default_mtls_endpoint(None) is None + assert FunctionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FunctionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FunctionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FunctionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FunctionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (FunctionServiceClient, "grpc"), + (FunctionServiceAsyncClient, "grpc_asyncio"), +]) +def test_function_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.FunctionServiceGrpcTransport, "grpc"), + (transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_function_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (FunctionServiceClient, "grpc"), + (FunctionServiceAsyncClient, "grpc_asyncio"), +]) +def test_function_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + + +def test_function_service_client_get_transport_class(): + transport = FunctionServiceClient.get_transport_class() + available_transports = [ + transports.FunctionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = FunctionServiceClient.get_transport_class("grpc") + assert transport == transports.FunctionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc"), + (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(FunctionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceClient)) +@mock.patch.object(FunctionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceAsyncClient)) +def test_function_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(FunctionServiceClient, '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(FunctionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + 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, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc", "true"), + (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc", "false"), + (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(FunctionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceClient)) +@mock.patch.object(FunctionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_function_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + FunctionServiceClient, FunctionServiceAsyncClient +]) +@mock.patch.object(FunctionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceClient)) +@mock.patch.object(FunctionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceAsyncClient)) +def test_function_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc"), + (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_function_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc", grpc_helpers), + (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_function_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_function_service_client_client_options_from_dict(): + with mock.patch('google.cloud.functions_v2.services.function_service.transports.FunctionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FunctionServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc", grpc_helpers), + (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_function_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudfunctions.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="cloudfunctions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + functions.GetFunctionRequest, + dict, +]) +def test_get_function(request_type, transport: str = 'grpc'): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.Function( + name='name_value', + environment=functions.Environment.GEN_1, + description='description_value', + state=functions.Function.State.ACTIVE, + ) + response = client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.Function) + assert response.name == 'name_value' + assert response.environment == functions.Environment.GEN_1 + assert response.description == 'description_value' + assert response.state == functions.Function.State.ACTIVE + + +def test_get_function_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 = FunctionServiceClient( + 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_function), + '__call__') as call: + client.get_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + +@pytest.mark.asyncio +async def test_get_function_async(transport: str = 'grpc_asyncio', request_type=functions.GetFunctionRequest): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.Function( + name='name_value', + environment=functions.Environment.GEN_1, + description='description_value', + state=functions.Function.State.ACTIVE, + )) + response = await client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.Function) + assert response.name == 'name_value' + assert response.environment == functions.Environment.GEN_1 + assert response.description == 'description_value' + assert response.state == functions.Function.State.ACTIVE + + +@pytest.mark.asyncio +async def test_get_function_async_from_dict(): + await test_get_function_async(request_type=dict) + + +def test_get_function_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GetFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + call.return_value = functions.Function() + client.get_function(request) + + # Establish that the 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_function_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GetFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.Function()) + await client.get_function(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_function_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.Function() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_function( + 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_function_flattened_error(): + client = FunctionServiceClient( + 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_function( + functions.GetFunctionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_function_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.Function() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.Function()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_function( + 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_function_flattened_error_async(): + client = FunctionServiceAsyncClient( + 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_function( + functions.GetFunctionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.ListFunctionsRequest, + dict, +]) +def test_list_functions(request_type, transport: str = 'grpc'): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_functions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListFunctionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFunctionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_functions_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 = FunctionServiceClient( + 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_functions), + '__call__') as call: + client.list_functions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + +@pytest.mark.asyncio +async def test_list_functions_async(transport: str = 'grpc_asyncio', request_type=functions.ListFunctionsRequest): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_functions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFunctionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_functions_async_from_dict(): + await test_list_functions_async(request_type=dict) + + +def test_list_functions_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListFunctionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__') as call: + call.return_value = functions.ListFunctionsResponse() + client.list_functions(request) + + # Establish that the 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_functions_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListFunctionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse()) + await client.list_functions(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_functions_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListFunctionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_functions( + 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_functions_flattened_error(): + client = FunctionServiceClient( + 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_functions( + functions.ListFunctionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_functions_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListFunctionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_functions( + 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_functions_flattened_error_async(): + client = FunctionServiceAsyncClient( + 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_functions( + functions.ListFunctionsRequest(), + parent='parent_value', + ) + + +def test_list_functions_pager(transport_name: str = "grpc"): + client = FunctionServiceClient( + 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_functions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + functions.Function(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_functions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, functions.Function) + for i in results) +def test_list_functions_pages(transport_name: str = "grpc"): + client = FunctionServiceClient( + 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_functions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + functions.Function(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + ], + ), + RuntimeError, + ) + pages = list(client.list_functions(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_functions_async_pager(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + functions.Function(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_functions(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, functions.Function) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_functions_async_pages(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + functions.Function(), + ], + next_page_token='abc', + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token='def', + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + ], + next_page_token='ghi', + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_functions(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", [ + functions.CreateFunctionRequest, + dict, +]) +def test_create_function(request_type, transport: str = 'grpc'): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_function_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 = FunctionServiceClient( + 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_function), + '__call__') as call: + client.create_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + +@pytest.mark.asyncio +async def test_create_function_async(transport: str = 'grpc_asyncio', request_type=functions.CreateFunctionRequest): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_function_async_from_dict(): + await test_create_function_async(request_type=dict) + + +def test_create_function_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CreateFunctionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_function(request) + + # Establish that the 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_function_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CreateFunctionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_function(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_function_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__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_function( + parent='parent_value', + function=functions.Function(name='name_value'), + function_id='function_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].function + mock_val = functions.Function(name='name_value') + assert arg == mock_val + arg = args[0].function_id + mock_val = 'function_id_value' + assert arg == mock_val + + +def test_create_function_flattened_error(): + client = FunctionServiceClient( + 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_function( + functions.CreateFunctionRequest(), + parent='parent_value', + function=functions.Function(name='name_value'), + function_id='function_id_value', + ) + +@pytest.mark.asyncio +async def test_create_function_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_function), + '__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_function( + parent='parent_value', + function=functions.Function(name='name_value'), + function_id='function_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].function + mock_val = functions.Function(name='name_value') + assert arg == mock_val + arg = args[0].function_id + mock_val = 'function_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_function_flattened_error_async(): + client = FunctionServiceAsyncClient( + 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_function( + functions.CreateFunctionRequest(), + parent='parent_value', + function=functions.Function(name='name_value'), + function_id='function_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.UpdateFunctionRequest, + dict, +]) +def test_update_function(request_type, transport: str = 'grpc'): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_function_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 = FunctionServiceClient( + 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_function), + '__call__') as call: + client.update_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + +@pytest.mark.asyncio +async def test_update_function_async(transport: str = 'grpc_asyncio', request_type=functions.UpdateFunctionRequest): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_function_async_from_dict(): + await test_update_function_async(request_type=dict) + + +def test_update_function_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.UpdateFunctionRequest() + + request.function.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_function(request) + + # Establish that the 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', + 'function.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_function_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.UpdateFunctionRequest() + + request.function.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_function(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', + 'function.name=name_value', + ) in kw['metadata'] + + +def test_update_function_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__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_function( + function=functions.Function(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].function + mock_val = functions.Function(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_function_flattened_error(): + client = FunctionServiceClient( + 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_function( + functions.UpdateFunctionRequest(), + function=functions.Function(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_function_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_function), + '__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_function( + function=functions.Function(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].function + mock_val = functions.Function(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_function_flattened_error_async(): + client = FunctionServiceAsyncClient( + 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_function( + functions.UpdateFunctionRequest(), + function=functions.Function(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + functions.DeleteFunctionRequest, + dict, +]) +def test_delete_function(request_type, transport: str = 'grpc'): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_function_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 = FunctionServiceClient( + 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_function), + '__call__') as call: + client.delete_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + +@pytest.mark.asyncio +async def test_delete_function_async(transport: str = 'grpc_asyncio', request_type=functions.DeleteFunctionRequest): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_function), + '__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_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_function_async_from_dict(): + await test_delete_function_async(request_type=dict) + + +def test_delete_function_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.DeleteFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_function(request) + + # Establish that the 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_function_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.DeleteFunctionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_function(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_function_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__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_function( + 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_function_flattened_error(): + client = FunctionServiceClient( + 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_function( + functions.DeleteFunctionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_function_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_function), + '__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_function( + 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_function_flattened_error_async(): + client = FunctionServiceAsyncClient( + 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_function( + functions.DeleteFunctionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + functions.GenerateUploadUrlRequest, + dict, +]) +def test_generate_upload_url(request_type, transport: str = 'grpc'): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.GenerateUploadUrlResponse( + upload_url='upload_url_value', + ) + response = client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateUploadUrlResponse) + assert response.upload_url == 'upload_url_value' + + +def test_generate_upload_url_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 = FunctionServiceClient( + 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.generate_upload_url), + '__call__') as call: + client.generate_upload_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + +@pytest.mark.asyncio +async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateUploadUrlRequest): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse( + upload_url='upload_url_value', + )) + response = await client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateUploadUrlResponse) + assert response.upload_url == 'upload_url_value' + + +@pytest.mark.asyncio +async def test_generate_upload_url_async_from_dict(): + await test_generate_upload_url_async(request_type=dict) + + +def test_generate_upload_url_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateUploadUrlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + call.return_value = functions.GenerateUploadUrlResponse() + client.generate_upload_url(request) + + # Establish that the 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_generate_upload_url_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateUploadUrlRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse()) + await client.generate_upload_url(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'] + + +@pytest.mark.parametrize("request_type", [ + functions.GenerateDownloadUrlRequest, + dict, +]) +def test_generate_download_url(request_type, transport: str = 'grpc'): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.GenerateDownloadUrlResponse( + download_url='download_url_value', + ) + response = client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateDownloadUrlResponse) + assert response.download_url == 'download_url_value' + + +def test_generate_download_url_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 = FunctionServiceClient( + 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.generate_download_url), + '__call__') as call: + client.generate_download_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + +@pytest.mark.asyncio +async def test_generate_download_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateDownloadUrlRequest): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse( + download_url='download_url_value', + )) + response = await client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateDownloadUrlResponse) + assert response.download_url == 'download_url_value' + + +@pytest.mark.asyncio +async def test_generate_download_url_async_from_dict(): + await test_generate_download_url_async(request_type=dict) + + +def test_generate_download_url_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateDownloadUrlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + call.return_value = functions.GenerateDownloadUrlResponse() + client.generate_download_url(request) + + # Establish that the 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_generate_download_url_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateDownloadUrlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse()) + await client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + functions.ListRuntimesRequest, + dict, +]) +def test_list_runtimes(request_type, transport: str = 'grpc'): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_runtimes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListRuntimesResponse( + ) + response = client.list_runtimes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListRuntimesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.ListRuntimesResponse) + + +def test_list_runtimes_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 = FunctionServiceClient( + 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_runtimes), + '__call__') as call: + client.list_runtimes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListRuntimesRequest() + +@pytest.mark.asyncio +async def test_list_runtimes_async(transport: str = 'grpc_asyncio', request_type=functions.ListRuntimesRequest): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_runtimes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.ListRuntimesResponse( + )) + response = await client.list_runtimes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListRuntimesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.ListRuntimesResponse) + + +@pytest.mark.asyncio +async def test_list_runtimes_async_from_dict(): + await test_list_runtimes_async(request_type=dict) + + +def test_list_runtimes_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListRuntimesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtimes), + '__call__') as call: + call.return_value = functions.ListRuntimesResponse() + client.list_runtimes(request) + + # Establish that the 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_runtimes_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListRuntimesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtimes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListRuntimesResponse()) + await client.list_runtimes(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_runtimes_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtimes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListRuntimesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_runtimes( + 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_runtimes_flattened_error(): + client = FunctionServiceClient( + 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_runtimes( + functions.ListRuntimesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_runtimes_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtimes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListRuntimesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListRuntimesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_runtimes( + 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_runtimes_flattened_error_async(): + client = FunctionServiceAsyncClient( + 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_runtimes( + functions.ListRuntimesRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FunctionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = FunctionServiceClient( + 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 = FunctionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FunctionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FunctionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FunctionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, +]) +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 = FunctionServiceClient.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 = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FunctionServiceGrpcTransport, + ) + +def test_function_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FunctionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_function_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FunctionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_function', + 'list_functions', + 'create_function', + 'update_function', + 'delete_function', + 'generate_upload_url', + 'generate_download_url', + 'list_runtimes', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'list_locations', + 'get_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_function_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FunctionServiceTransport( + 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_function_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FunctionServiceTransport() + adc.assert_called_once() + + +def test_function_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FunctionServiceClient() + 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.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) +def test_function_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) +def test_function_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FunctionServiceGrpcTransport, grpc_helpers), + (transports.FunctionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_function_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "cloudfunctions.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="cloudfunctions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.FunctionServiceGrpcTransport, transports.FunctionServiceGrpcAsyncIOTransport]) +def test_function_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_function_service_host_no_port(transport_name): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_function_service_host_with_port(transport_name): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudfunctions.googleapis.com:8000' + ) + +def test_function_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FunctionServiceGrpcTransport( + 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_function_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FunctionServiceGrpcAsyncIOTransport( + 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.FunctionServiceGrpcTransport, transports.FunctionServiceGrpcAsyncIOTransport]) +def test_function_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.FunctionServiceGrpcTransport, transports.FunctionServiceGrpcAsyncIOTransport]) +def test_function_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_function_service_grpc_lro_client(): + client = FunctionServiceClient( + 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_function_service_grpc_lro_async_client(): + client = FunctionServiceAsyncClient( + 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_build_path(): + project = "squid" + location = "clam" + build = "whelk" + expected = "projects/{project}/locations/{location}/builds/{build}".format(project=project, location=location, build=build, ) + actual = FunctionServiceClient.build_path(project, location, build) + assert expected == actual + + +def test_parse_build_path(): + expected = { + "project": "octopus", + "location": "oyster", + "build": "nudibranch", + } + path = FunctionServiceClient.build_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_build_path(path) + assert expected == actual + +def test_channel_path(): + project = "cuttlefish" + location = "mussel" + channel = "winkle" + expected = "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) + actual = FunctionServiceClient.channel_path(project, location, channel) + assert expected == actual + + +def test_parse_channel_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "channel": "abalone", + } + path = FunctionServiceClient.channel_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_channel_path(path) + assert expected == actual + +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 = FunctionServiceClient.connector_path(project, location, connector) + assert expected == actual + + +def test_parse_connector_path(): + expected = { + "project": "octopus", + "location": "oyster", + "connector": "nudibranch", + } + path = FunctionServiceClient.connector_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_connector_path(path) + assert expected == actual + +def test_function_path(): + project = "cuttlefish" + location = "mussel" + function = "winkle" + expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + actual = FunctionServiceClient.function_path(project, location, function) + assert expected == actual + + +def test_parse_function_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "function": "abalone", + } + path = FunctionServiceClient.function_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_function_path(path) + assert expected == actual + +def test_repository_path(): + project = "squid" + location = "clam" + repository = "whelk" + expected = "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) + actual = FunctionServiceClient.repository_path(project, location, repository) + assert expected == actual + + +def test_parse_repository_path(): + expected = { + "project": "octopus", + "location": "oyster", + "repository": "nudibranch", + } + path = FunctionServiceClient.repository_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_repository_path(path) + assert expected == actual + +def test_service_path(): + project = "cuttlefish" + location = "mussel" + service = "winkle" + expected = "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) + actual = FunctionServiceClient.service_path(project, location, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "service": "abalone", + } + path = FunctionServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_service_path(path) + assert expected == actual + +def test_topic_path(): + project = "squid" + topic = "clam" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = FunctionServiceClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "whelk", + "topic": "octopus", + } + path = FunctionServiceClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_topic_path(path) + assert expected == actual + +def test_trigger_path(): + project = "oyster" + location = "nudibranch" + trigger = "cuttlefish" + expected = "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) + actual = FunctionServiceClient.trigger_path(project, location, trigger) + assert expected == actual + + +def test_parse_trigger_path(): + expected = { + "project": "mussel", + "location": "winkle", + "trigger": "nautilus", + } + path = FunctionServiceClient.trigger_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_trigger_path(path) + assert expected == actual + +def test_worker_pool_path(): + project = "scallop" + location = "abalone" + worker_pool = "squid" + expected = "projects/{project}/locations/{location}/workerPools/{worker_pool}".format(project=project, location=location, worker_pool=worker_pool, ) + actual = FunctionServiceClient.worker_pool_path(project, location, worker_pool) + assert expected == actual + + +def test_parse_worker_pool_path(): + expected = { + "project": "clam", + "location": "whelk", + "worker_pool": "octopus", + } + path = FunctionServiceClient.worker_pool_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_worker_pool_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FunctionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = FunctionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = FunctionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = FunctionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FunctionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = FunctionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = FunctionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = FunctionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = FunctionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = FunctionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.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.FunctionServiceTransport, '_prep_wrapped_messages') as prep: + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FunctionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = FunctionServiceClient.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 = FunctionServiceAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation(transport: str = "grpc"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations(transport: str = "grpc"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations(transport: str = "grpc"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = FunctionServiceAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = FunctionServiceAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = FunctionServiceAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = FunctionServiceClient( + 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 = FunctionServiceClient( + 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", [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport), + (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport), +]) +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, + api_audience=None, + ) From 8dc2769e2d4fcef3f428727b154bb1aae59ac98b Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 6 Jul 2022 20:50:02 +0000 Subject: [PATCH 06/16] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-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 --- .../functions_v2/function_service.rst | 0 .../docs => docs}/functions_v2/services.rst | 0 .../v2/docs => docs}/functions_v2/types.rst | 0 docs/index.rst | 11 + google/cloud/functions_v2/__init__.py | 78 + .../cloud/functions_v2/gapic_metadata.json | 0 .../cloud/functions_v2}/py.typed | 0 .../cloud/functions_v2}/services/__init__.py | 0 .../services/function_service/__init__.py | 6 +- .../services/function_service/async_client.py | 338 +- .../services/function_service/client.py | 592 ++- .../services/function_service/pagers.py | 46 +- .../function_service/transports/__init__.py | 11 +- .../function_service/transports/base.py | 207 +- .../function_service/transports/grpc.py | 219 +- .../transports/grpc_asyncio.py | 225 +- .../cloud/functions_v2/types/__init__.py | 56 +- .../cloud/functions_v2/types/functions.py | 120 +- owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/.flake8 | 33 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 -- .../functions_v1/cloud_functions_service.rst | 10 - .../v1/docs/functions_v1/services.rst | 6 - .../v1/docs/functions_v1/types.rst | 7 - owl-bot-staging/v1/docs/index.rst | 7 - .../v1/google/cloud/functions/__init__.py | 67 - .../v1/google/cloud/functions_v1/__init__.py | 68 - .../cloud/functions_v1/gapic_metadata.json | 133 - .../v1/google/cloud/functions_v1/py.typed | 2 - .../cloud_functions_service/__init__.py | 22 - .../cloud_functions_service/async_client.py | 1423 ------- .../cloud_functions_service/client.py | 1613 -------- .../cloud_functions_service/pagers.py | 139 - .../transports/__init__.py | 33 - .../transports/base.py | 331 -- .../transports/grpc.py | 593 --- .../transports/grpc_asyncio.py | 592 --- .../cloud/functions_v1/types/__init__.py | 66 - .../cloud/functions_v1/types/functions.py | 1067 ----- .../cloud/functions_v1/types/operations.py | 108 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 180 - ...d_functions_service_call_function_async.py | 46 - ...ud_functions_service_call_function_sync.py | 46 - ...functions_service_create_function_async.py | 53 - ..._functions_service_create_function_sync.py | 53 - ...functions_service_delete_function_async.py | 49 - ..._functions_service_delete_function_sync.py | 49 - ...ons_service_generate_download_url_async.py | 44 - ...ions_service_generate_download_url_sync.py | 44 - ...tions_service_generate_upload_url_async.py | 44 - ...ctions_service_generate_upload_url_sync.py | 44 - ...ud_functions_service_get_function_async.py | 45 - ...oud_functions_service_get_function_sync.py | 45 - ..._functions_service_get_iam_policy_async.py | 46 - ...d_functions_service_get_iam_policy_sync.py | 46 - ..._functions_service_list_functions_async.py | 45 - ...d_functions_service_list_functions_sync.py | 45 - ..._functions_service_set_iam_policy_async.py | 46 - ...d_functions_service_set_iam_policy_sync.py | 46 - ...ions_service_test_iam_permissions_async.py | 47 - ...tions_service_test_iam_permissions_sync.py | 47 - ...functions_service_update_function_async.py | 52 - ..._functions_service_update_function_sync.py | 52 - .../snippet_metadata_functions_v1.json | 1753 -------- .../v1/scripts/fixup_functions_v1_keywords.py | 186 - owl-bot-staging/v1/setup.py | 60 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/functions_v1/__init__.py | 16 - .../test_cloud_functions_service.py | 3681 ----------------- 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 - .../v2/google/cloud/functions/__init__.py | 77 - .../v2/google/cloud/functions/py.typed | 2 - .../v2/google/cloud/functions_v2/__init__.py | 78 - .../v2/google/cloud/functions_v2/py.typed | 2 - owl-bot-staging/v2/mypy.ini | 3 - owl-bot-staging/v2/noxfile.py | 180 - 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 - .../tests/unit/gapic/functions_v2/__init__.py | 16 - ..._function_service_create_function_async.py | 0 ...d_function_service_create_function_sync.py | 0 ..._function_service_delete_function_async.py | 0 ...d_function_service_delete_function_sync.py | 0 ...ion_service_generate_download_url_async.py | 0 ...tion_service_generate_download_url_sync.py | 0 ...ction_service_generate_upload_url_async.py | 0 ...nction_service_generate_upload_url_sync.py | 0 ...ted_function_service_get_function_async.py | 0 ...ated_function_service_get_function_sync.py | 0 ...d_function_service_list_functions_async.py | 0 ...ed_function_service_list_functions_sync.py | 0 ...ed_function_service_list_runtimes_async.py | 0 ...ted_function_service_list_runtimes_sync.py | 0 ..._function_service_update_function_async.py | 0 ...d_function_service_update_function_sync.py | 0 .../snippet_metadata_functions_v2.json | 0 .../fixup_functions_v2_keywords.py | 0 .../unit/gapic/functions_v2}/__init__.py | 0 .../functions_v2/test_function_service.py | 1820 ++++---- 111 files changed, 2238 insertions(+), 16166 deletions(-) rename {owl-bot-staging/v2/docs => docs}/functions_v2/function_service.rst (100%) rename {owl-bot-staging/v2/docs => docs}/functions_v2/services.rst (100%) rename {owl-bot-staging/v2/docs => docs}/functions_v2/types.rst (100%) create mode 100644 google/cloud/functions_v2/__init__.py rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/gapic_metadata.json (100%) rename {owl-bot-staging/v1/google/cloud/functions => google/cloud/functions_v2}/py.typed (100%) rename {owl-bot-staging/v1/google/cloud/functions_v1 => google/cloud/functions_v2}/services/__init__.py (100%) rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/services/function_service/__init__.py (91%) rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/services/function_service/async_client.py (88%) rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/services/function_service/client.py (82%) rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/services/function_service/pagers.py (86%) rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/services/function_service/transports/__init__.py (80%) rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/services/function_service/transports/base.py (65%) rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/services/function_service/transports/grpc.py (82%) rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py (82%) rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/types/__init__.py (65%) rename {owl-bot-staging/v2/google => google}/cloud/functions_v2/types/functions.py (96%) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/.flake8 delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst delete mode 100644 owl-bot-staging/v1/docs/functions_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/functions_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/google/cloud/functions/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py delete mode 100644 owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json delete mode 100644 owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py 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/google/cloud/functions/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/functions/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/functions_v2/py.typed 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/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/functions_v2/__init__.py rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py (100%) rename {owl-bot-staging/v2/samples => samples}/generated_samples/snippet_metadata_functions_v2.json (100%) rename {owl-bot-staging/v2/scripts => scripts}/fixup_functions_v2_keywords.py (100%) rename {owl-bot-staging/v2/google/cloud/functions_v2/services => tests/unit/gapic/functions_v2}/__init__.py (100%) rename {owl-bot-staging/v2/tests => tests}/unit/gapic/functions_v2/test_function_service.py (77%) diff --git a/owl-bot-staging/v2/docs/functions_v2/function_service.rst b/docs/functions_v2/function_service.rst similarity index 100% rename from owl-bot-staging/v2/docs/functions_v2/function_service.rst rename to docs/functions_v2/function_service.rst diff --git a/owl-bot-staging/v2/docs/functions_v2/services.rst b/docs/functions_v2/services.rst similarity index 100% rename from owl-bot-staging/v2/docs/functions_v2/services.rst rename to docs/functions_v2/services.rst diff --git a/owl-bot-staging/v2/docs/functions_v2/types.rst b/docs/functions_v2/types.rst similarity index 100% rename from owl-bot-staging/v2/docs/functions_v2/types.rst rename to docs/functions_v2/types.rst diff --git a/docs/index.rst b/docs/index.rst index 7537b90..15bb7cd 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -2,6 +2,9 @@ .. include:: multiprocessing.rst +This package includes clients for multiple versions of Cloud Functions. +By default, you will get version ``functions_v1``. + API Reference ------------- @@ -11,6 +14,14 @@ API Reference functions_v1/services functions_v1/types +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + functions_v2/services + functions_v2/types + Changelog --------- diff --git a/google/cloud/functions_v2/__init__.py b/google/cloud/functions_v2/__init__.py new file mode 100644 index 0000000..8810a81 --- /dev/null +++ b/google/cloud/functions_v2/__init__.py @@ -0,0 +1,78 @@ +# -*- 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.function_service import FunctionServiceAsyncClient, FunctionServiceClient +from .types.functions import ( + BuildConfig, + CreateFunctionRequest, + DeleteFunctionRequest, + Environment, + EventFilter, + EventTrigger, + Function, + GenerateDownloadUrlRequest, + GenerateDownloadUrlResponse, + GenerateUploadUrlRequest, + GenerateUploadUrlResponse, + GetFunctionRequest, + ListFunctionsRequest, + ListFunctionsResponse, + ListRuntimesRequest, + ListRuntimesResponse, + OperationMetadata, + RepoSource, + SecretEnvVar, + SecretVolume, + ServiceConfig, + Source, + SourceProvenance, + Stage, + StateMessage, + StorageSource, + UpdateFunctionRequest, +) + +__all__ = ( + "FunctionServiceAsyncClient", + "BuildConfig", + "CreateFunctionRequest", + "DeleteFunctionRequest", + "Environment", + "EventFilter", + "EventTrigger", + "Function", + "FunctionServiceClient", + "GenerateDownloadUrlRequest", + "GenerateDownloadUrlResponse", + "GenerateUploadUrlRequest", + "GenerateUploadUrlResponse", + "GetFunctionRequest", + "ListFunctionsRequest", + "ListFunctionsResponse", + "ListRuntimesRequest", + "ListRuntimesResponse", + "OperationMetadata", + "RepoSource", + "SecretEnvVar", + "SecretVolume", + "ServiceConfig", + "Source", + "SourceProvenance", + "Stage", + "StateMessage", + "StorageSource", + "UpdateFunctionRequest", +) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/gapic_metadata.json b/google/cloud/functions_v2/gapic_metadata.json similarity index 100% rename from owl-bot-staging/v2/google/cloud/functions_v2/gapic_metadata.json rename to google/cloud/functions_v2/gapic_metadata.json diff --git a/owl-bot-staging/v1/google/cloud/functions/py.typed b/google/cloud/functions_v2/py.typed similarity index 100% rename from owl-bot-staging/v1/google/cloud/functions/py.typed rename to google/cloud/functions_v2/py.typed diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py b/google/cloud/functions_v2/services/__init__.py similarity index 100% rename from owl-bot-staging/v1/google/cloud/functions_v1/services/__init__.py rename to google/cloud/functions_v2/services/__init__.py diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/__init__.py b/google/cloud/functions_v2/services/function_service/__init__.py similarity index 91% rename from owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/__init__.py rename to google/cloud/functions_v2/services/function_service/__init__.py index c8ef801..73f00d9 100644 --- a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/__init__.py +++ b/google/cloud/functions_v2/services/function_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import FunctionServiceClient from .async_client import FunctionServiceAsyncClient +from .client import FunctionServiceClient __all__ = ( - 'FunctionServiceClient', - 'FunctionServiceAsyncClient', + "FunctionServiceClient", + "FunctionServiceAsyncClient", ) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/async_client.py b/google/cloud/functions_v2/services/function_service/async_client.py similarity index 88% rename from owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/async_client.py rename to google/cloud/functions_v2/services/function_service/async_client.py index fd460a0..70a1568 100644 --- a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/async_client.py +++ b/google/cloud/functions_v2/services/function_service/async_client.py @@ -17,14 +17,14 @@ 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 +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import pkg_resources try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -33,18 +33,20 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.types import functions -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore 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 from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FunctionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport + +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.types import functions + from .client import FunctionServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, FunctionServiceTransport +from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport class FunctionServiceAsyncClient: @@ -79,16 +81,30 @@ class FunctionServiceAsyncClient: parse_trigger_path = staticmethod(FunctionServiceClient.parse_trigger_path) worker_pool_path = staticmethod(FunctionServiceClient.worker_pool_path) parse_worker_pool_path = staticmethod(FunctionServiceClient.parse_worker_pool_path) - common_billing_account_path = staticmethod(FunctionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(FunctionServiceClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + FunctionServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + FunctionServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(FunctionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(FunctionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(FunctionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(FunctionServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + FunctionServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + FunctionServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + FunctionServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(FunctionServiceClient.common_project_path) - parse_common_project_path = staticmethod(FunctionServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + FunctionServiceClient.parse_common_project_path + ) common_location_path = staticmethod(FunctionServiceClient.common_location_path) - parse_common_location_path = staticmethod(FunctionServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + FunctionServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -124,7 +140,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + 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: @@ -166,14 +184,18 @@ def transport(self) -> FunctionServiceTransport: """ return self._client.transport - get_transport_class = functools.partial(type(FunctionServiceClient).get_transport_class, type(FunctionServiceClient)) + get_transport_class = functools.partial( + type(FunctionServiceClient).get_transport_class, type(FunctionServiceClient) + ) - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, FunctionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FunctionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the function service client. Args: @@ -211,17 +233,17 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - async def get_function(self, - request: Union[functions.GetFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.Function: + async def get_function( + self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.Function: r"""Returns a function with the given name from the requested project. @@ -274,8 +296,10 @@ async def sample_get_function(): # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = functions.GetFunctionRequest(request) @@ -295,9 +319,7 @@ async def sample_get_function(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -311,14 +333,15 @@ async def sample_get_function(): # Done; return the response. return response - async def list_functions(self, - request: Union[functions.ListFunctionsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsAsyncPager: + async def list_functions( + self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsAsyncPager: r"""Returns a list of functions that belong to the requested project. @@ -378,8 +401,10 @@ async def sample_list_functions(): # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = functions.ListFunctionsRequest(request) @@ -399,9 +424,7 @@ async def sample_list_functions(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -424,16 +447,17 @@ async def sample_list_functions(): # Done; return the response. return response - async def create_function(self, - request: Union[functions.CreateFunctionRequest, dict] = None, - *, - parent: str = None, - function: functions.Function = None, - function_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: + async def create_function( + self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + parent: str = None, + function: functions.Function = None, + function_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: r"""Creates a new function. If a function with the given name already exists in the specified project, the long running operation will return ``ALREADY_EXISTS`` error. @@ -508,8 +532,10 @@ async def sample_create_function(): # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, function, function_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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = functions.CreateFunctionRequest(request) @@ -533,9 +559,7 @@ async def sample_create_function(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -557,15 +581,16 @@ async def sample_create_function(): # Done; return the response. return response - async def update_function(self, - request: Union[functions.UpdateFunctionRequest, dict] = None, - *, - function: functions.Function = 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: + async def update_function( + self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.Function = 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 existing function. .. code-block:: python @@ -630,8 +655,10 @@ async def sample_update_function(): # gotten any keyword arguments that map to the request. has_flattened_params = any([function, 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = functions.UpdateFunctionRequest(request) @@ -653,9 +680,9 @@ async def sample_update_function(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("function.name", request.function.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("function.name", request.function.name),) + ), ) # Send the request. @@ -677,14 +704,15 @@ async def sample_update_function(): # Done; return the response. return response - async def delete_function(self, - request: Union[functions.DeleteFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: + async def delete_function( + self, + request: Union[functions.DeleteFunctionRequest, 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 function with the given name from the specified project. If the given function is used by some trigger, the trigger will be updated to remove this @@ -754,8 +782,10 @@ async def sample_delete_function(): # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = functions.DeleteFunctionRequest(request) @@ -775,9 +805,7 @@ async def sample_delete_function(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -799,13 +827,14 @@ async def sample_delete_function(): # Done; return the response. return response - async def generate_upload_url(self, - request: Union[functions.GenerateUploadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateUploadUrlResponse: + async def generate_upload_url( + self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: r"""Returns a signed URL for uploading a function source code. For more information about the signed URL usage see: https://cloud.google.com/storage/docs/access-control/signed-urls. @@ -880,9 +909,7 @@ async def sample_generate_upload_url(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -896,13 +923,14 @@ async def sample_generate_upload_url(): # Done; return the response. return response - async def generate_download_url(self, - request: Union[functions.GenerateDownloadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateDownloadUrlResponse: + async def generate_download_url( + self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: r"""Returns a signed URL for downloading deployed function source code. The URL is only valid for a limited period and should be used within 30 minutes of @@ -957,9 +985,7 @@ async def sample_generate_download_url(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -973,14 +999,15 @@ async def sample_generate_download_url(): # Done; return the response. return response - async def list_runtimes(self, - request: Union[functions.ListRuntimesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.ListRuntimesResponse: + async def list_runtimes( + self, + request: Union[functions.ListRuntimesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.ListRuntimesResponse: r"""Returns a list of runtimes that are supported for the requested project. @@ -1030,8 +1057,10 @@ async def sample_list_runtimes(): # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = functions.ListRuntimesRequest(request) @@ -1051,9 +1080,7 @@ async def sample_list_runtimes(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -1107,13 +1134,16 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1158,13 +1188,16 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1268,13 +1301,16 @@ async def 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),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1379,13 +1415,16 @@ async def 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),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1435,13 +1474,16 @@ async def 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),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1486,13 +1528,16 @@ async def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1503,6 +1548,7 @@ async def __aenter__(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( @@ -1513,6 +1559,4 @@ async def __aexit__(self, exc_type, exc, tb): DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "FunctionServiceAsyncClient", -) +__all__ = ("FunctionServiceAsyncClient",) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/client.py b/google/cloud/functions_v2/services/function_service/client.py similarity index 82% rename from owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/client.py rename to google/cloud/functions_v2/services/function_service/client.py index f9457ef..e4e6484 100644 --- a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/client.py +++ b/google/cloud/functions_v2/services/function_service/client.py @@ -17,17 +17,17 @@ 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 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import pkg_resources try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -36,16 +36,18 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.types import functions -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore 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 from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FunctionServiceTransport, DEFAULT_CLIENT_INFO + +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.types import functions + +from .transports.base import DEFAULT_CLIENT_INFO, FunctionServiceTransport from .transports.grpc import FunctionServiceGrpcTransport from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport @@ -57,13 +59,17 @@ class FunctionServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[FunctionServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[FunctionServiceTransport]] _transport_registry["grpc"] = FunctionServiceGrpcTransport _transport_registry["grpc_asyncio"] = FunctionServiceGrpcAsyncIOTransport - def get_transport_class(cls, - label: str = None, - ) -> Type[FunctionServiceTransport]: + def get_transport_class( + cls, + label: str = None, + ) -> Type[FunctionServiceTransport]: """Returns an appropriate transport class. Args: @@ -157,8 +163,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: FunctionServiceClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -175,161 +180,283 @@ def transport(self) -> FunctionServiceTransport: return self._transport @staticmethod - def build_path(project: str,location: str,build: str,) -> str: + def build_path( + project: str, + location: str, + build: str, + ) -> str: """Returns a fully-qualified build string.""" - return "projects/{project}/locations/{location}/builds/{build}".format(project=project, location=location, build=build, ) + return "projects/{project}/locations/{location}/builds/{build}".format( + project=project, + location=location, + build=build, + ) @staticmethod - def parse_build_path(path: str) -> Dict[str,str]: + def parse_build_path(path: str) -> Dict[str, str]: """Parses a build path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/builds/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/builds/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def channel_path(project: str,location: str,channel: str,) -> str: + def channel_path( + project: str, + location: str, + channel: str, + ) -> str: """Returns a fully-qualified channel string.""" - return "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) + return "projects/{project}/locations/{location}/channels/{channel}".format( + project=project, + location=location, + channel=channel, + ) @staticmethod - def parse_channel_path(path: str) -> Dict[str,str]: + def parse_channel_path(path: str) -> Dict[str, str]: """Parses a channel path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def connector_path(project: str,location: str,connector: str,) -> str: + 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, ) + return "projects/{project}/locations/{location}/connectors/{connector}".format( + project=project, + location=location, + connector=connector, + ) @staticmethod - def parse_connector_path(path: str) -> Dict[str,str]: + 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) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/connectors/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def function_path(project: str,location: str,function: str,) -> str: + def function_path( + project: str, + location: str, + function: str, + ) -> str: """Returns a fully-qualified function string.""" - return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + return "projects/{project}/locations/{location}/functions/{function}".format( + project=project, + location=location, + function=function, + ) @staticmethod - def parse_function_path(path: str) -> Dict[str,str]: + def parse_function_path(path: str) -> Dict[str, str]: """Parses a function path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def repository_path(project: str,location: str,repository: str,) -> str: + def repository_path( + project: str, + location: str, + repository: str, + ) -> str: """Returns a fully-qualified repository string.""" - return "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) + return ( + "projects/{project}/locations/{location}/repositories/{repository}".format( + project=project, + location=location, + repository=repository, + ) + ) @staticmethod - def parse_repository_path(path: str) -> Dict[str,str]: + def parse_repository_path(path: str) -> Dict[str, str]: """Parses a repository path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/repositories/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/repositories/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def service_path(project: str,location: str,service: str,) -> str: + 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, ) + return "projects/{project}/locations/{location}/services/{service}".format( + project=project, + location=location, + service=service, + ) @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: + 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) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def topic_path(project: str,topic: str,) -> str: + def topic_path( + project: str, + topic: str, + ) -> str: """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + return "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: + def parse_topic_path(path: str) -> Dict[str, str]: """Parses a topic path into its component segments.""" m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def trigger_path(project: str,location: str,trigger: str,) -> str: + def trigger_path( + project: str, + location: str, + trigger: str, + ) -> str: """Returns a fully-qualified trigger string.""" - return "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) + return "projects/{project}/locations/{location}/triggers/{trigger}".format( + project=project, + location=location, + trigger=trigger, + ) @staticmethod - def parse_trigger_path(path: str) -> Dict[str,str]: + def parse_trigger_path(path: str) -> Dict[str, str]: """Parses a trigger path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def worker_pool_path(project: str,location: str,worker_pool: str,) -> str: + def worker_pool_path( + project: str, + location: str, + worker_pool: str, + ) -> str: """Returns a fully-qualified worker_pool string.""" - return "projects/{project}/locations/{location}/workerPools/{worker_pool}".format(project=project, location=location, worker_pool=worker_pool, ) + return ( + "projects/{project}/locations/{location}/workerPools/{worker_pool}".format( + project=project, + location=location, + worker_pool=worker_pool, + ) + ) @staticmethod - def parse_worker_pool_path(path: str) -> Dict[str,str]: + def parse_worker_pool_path(path: str) -> Dict[str, str]: """Parses a worker_pool path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workerPools/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/workerPools/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + 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, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + 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: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + 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: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + 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: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + 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): + 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: @@ -365,9 +492,13 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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`") + 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`") + 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 @@ -380,19 +511,23 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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): + 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, FunctionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FunctionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the function service client. Args: @@ -435,11 +570,15 @@ def __init__(self, *, 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_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") + 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 @@ -447,8 +586,10 @@ def __init__(self, *, if isinstance(transport, FunctionServiceTransport): # transport is a FunctionServiceTransport instance. if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + 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 " @@ -458,8 +599,12 @@ def __init__(self, *, 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) + 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( @@ -474,14 +619,15 @@ def __init__(self, *, api_audience=client_options.api_audience, ) - def get_function(self, - request: Union[functions.GetFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.Function: + def get_function( + self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.Function: r"""Returns a function with the given name from the requested project. @@ -534,8 +680,10 @@ def sample_get_function(): # 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.') + 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 functions.GetFunctionRequest. @@ -552,12 +700,10 @@ def sample_get_function(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.get_function] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -571,14 +717,15 @@ def sample_get_function(): # Done; return the response. return response - def list_functions(self, - request: Union[functions.ListFunctionsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsPager: + def list_functions( + self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsPager: r"""Returns a list of functions that belong to the requested project. @@ -638,8 +785,10 @@ def sample_list_functions(): # 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.') + 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 functions.ListFunctionsRequest. @@ -656,12 +805,10 @@ def sample_list_functions(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.list_functions] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -684,16 +831,17 @@ def sample_list_functions(): # Done; return the response. return response - def create_function(self, - request: Union[functions.CreateFunctionRequest, dict] = None, - *, - parent: str = None, - function: functions.Function = None, - function_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: + def create_function( + self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + parent: str = None, + function: functions.Function = None, + function_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: r"""Creates a new function. If a function with the given name already exists in the specified project, the long running operation will return ``ALREADY_EXISTS`` error. @@ -768,8 +916,10 @@ def sample_create_function(): # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, function, function_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.') + 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 functions.CreateFunctionRequest. @@ -790,12 +940,10 @@ def sample_create_function(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.create_function] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -817,15 +965,16 @@ def sample_create_function(): # Done; return the response. return response - def update_function(self, - request: Union[functions.UpdateFunctionRequest, dict] = None, - *, - function: functions.Function = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: + def update_function( + self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.Function = 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 existing function. .. code-block:: python @@ -890,8 +1039,10 @@ def sample_update_function(): # gotten any keyword arguments that map to the request. has_flattened_params = any([function, 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.') + 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 functions.UpdateFunctionRequest. @@ -910,12 +1061,12 @@ def sample_update_function(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.update_function] - # Certain fields should be provided within the metadata header; + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("function.name", request.function.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("function.name", request.function.name),) + ), ) # Send the request. @@ -937,14 +1088,15 @@ def sample_update_function(): # Done; return the response. return response - def delete_function(self, - request: Union[functions.DeleteFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: + def delete_function( + self, + request: Union[functions.DeleteFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: r"""Deletes a function with the given name from the specified project. If the given function is used by some trigger, the trigger will be updated to remove this @@ -1014,8 +1166,10 @@ def sample_delete_function(): # 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.') + 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 functions.DeleteFunctionRequest. @@ -1032,12 +1186,10 @@ def sample_delete_function(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.delete_function] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -1059,13 +1211,14 @@ def sample_delete_function(): # Done; return the response. return response - def generate_upload_url(self, - request: Union[functions.GenerateUploadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateUploadUrlResponse: + def generate_upload_url( + self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: r"""Returns a signed URL for uploading a function source code. For more information about the signed URL usage see: https://cloud.google.com/storage/docs/access-control/signed-urls. @@ -1138,12 +1291,10 @@ def sample_generate_upload_url(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.generate_upload_url] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -1157,13 +1308,14 @@ def sample_generate_upload_url(): # Done; return the response. return response - def generate_download_url(self, - request: Union[functions.GenerateDownloadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateDownloadUrlResponse: + def generate_download_url( + self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: r"""Returns a signed URL for downloading deployed function source code. The URL is only valid for a limited period and should be used within 30 minutes of @@ -1216,12 +1368,10 @@ def sample_generate_download_url(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.generate_download_url] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -1235,14 +1385,15 @@ def sample_generate_download_url(): # Done; return the response. return response - def list_runtimes(self, - request: Union[functions.ListRuntimesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.ListRuntimesResponse: + def list_runtimes( + self, + request: Union[functions.ListRuntimesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.ListRuntimesResponse: r"""Returns a list of runtimes that are supported for the requested project. @@ -1292,8 +1443,10 @@ def sample_list_runtimes(): # 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.') + 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 functions.ListRuntimesRequest. @@ -1310,12 +1463,10 @@ def sample_list_runtimes(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.list_runtimes] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -1382,13 +1533,16 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1433,13 +1587,16 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1543,13 +1700,16 @@ def 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),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1654,13 +1814,16 @@ def 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),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1710,13 +1873,16 @@ def 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),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1761,17 +1927,21 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -1782,6 +1952,4 @@ def list_locations( DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "FunctionServiceClient", -) +__all__ = ("FunctionServiceClient",) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/pagers.py b/google/cloud/functions_v2/services/function_service/pagers.py similarity index 86% rename from owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/pagers.py rename to google/cloud/functions_v2/services/function_service/pagers.py index 4e6acec..08de657 100644 --- a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/pagers.py +++ b/google/cloud/functions_v2/services/function_service/pagers.py @@ -13,7 +13,16 @@ # 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 typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) from google.cloud.functions_v2.types import functions @@ -35,12 +44,15 @@ class ListFunctionsPager: 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[..., functions.ListFunctionsResponse], - request: functions.ListFunctionsRequest, - response: functions.ListFunctionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): + + def __init__( + self, + method: Callable[..., functions.ListFunctionsResponse], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiate the pager. Args: @@ -74,7 +86,7 @@ def __iter__(self) -> Iterator[functions.Function]: yield from page.functions def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListFunctionsAsyncPager: @@ -94,12 +106,15 @@ class ListFunctionsAsyncPager: 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[functions.ListFunctionsResponse]], - request: functions.ListFunctionsRequest, - response: functions.ListFunctionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): + + def __init__( + self, + method: Callable[..., Awaitable[functions.ListFunctionsResponse]], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiates the pager. Args: @@ -127,6 +142,7 @@ async def pages(self) -> AsyncIterator[functions.ListFunctionsResponse]: 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[functions.Function]: async def async_generator(): async for page in self.pages: @@ -136,4 +152,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/__init__.py b/google/cloud/functions_v2/services/function_service/transports/__init__.py similarity index 80% rename from owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/__init__.py rename to google/cloud/functions_v2/services/function_service/transports/__init__.py index 5a68cc5..cc0b207 100644 --- a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/__init__.py +++ b/google/cloud/functions_v2/services/function_service/transports/__init__.py @@ -20,14 +20,13 @@ from .grpc import FunctionServiceGrpcTransport from .grpc_asyncio import FunctionServiceGrpcAsyncIOTransport - # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[FunctionServiceTransport]] -_transport_registry['grpc'] = FunctionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = FunctionServiceGrpcAsyncIOTransport +_transport_registry["grpc"] = FunctionServiceGrpcTransport +_transport_registry["grpc_asyncio"] = FunctionServiceGrpcAsyncIOTransport __all__ = ( - 'FunctionServiceTransport', - 'FunctionServiceGrpcTransport', - 'FunctionServiceGrpcAsyncIOTransport', + "FunctionServiceTransport", + "FunctionServiceGrpcTransport", + "FunctionServiceGrpcAsyncIOTransport", ) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/base.py b/google/cloud/functions_v2/services/function_service/transports/base.py similarity index 65% rename from owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/base.py rename to google/cloud/functions_v2/services/function_service/transports/base.py index 1c3faad..ab49afa 100644 --- a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/base.py +++ b/google/cloud/functions_v2/services/function_service/transports/base.py @@ -15,28 +15,26 @@ # 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 gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.functions_v2.types import functions -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore 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 from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import pkg_resources + +from google.cloud.functions_v2.types import functions try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - 'google-cloud-functions', + "google-cloud-functions", ).version, ) except pkg_resources.DistributionNotFound: @@ -46,23 +44,23 @@ class FunctionServiceTransport(abc.ABC): """Abstract transport class for FunctionService.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "cloudfunctions.googleapis.com" - DEFAULT_HOST: str = 'cloudfunctions.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, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + 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, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -96,30 +94,38 @@ def __init__( # 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") + 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 - ) + 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) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host def _prep_wrapped_messages(self, client_info): @@ -165,14 +171,14 @@ def _prep_wrapped_messages(self, client_info): 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! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -182,75 +188,85 @@ def operations_client(self): raise NotImplementedError() @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - Union[ - functions.Function, - Awaitable[functions.Function] - ]]: + def get_function( + self, + ) -> Callable[ + [functions.GetFunctionRequest], + Union[functions.Function, Awaitable[functions.Function]], + ]: raise NotImplementedError() @property - def list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - Union[ - functions.ListFunctionsResponse, - Awaitable[functions.ListFunctionsResponse] - ]]: + def list_functions( + self, + ) -> Callable[ + [functions.ListFunctionsRequest], + Union[ + functions.ListFunctionsResponse, Awaitable[functions.ListFunctionsResponse] + ], + ]: raise NotImplementedError() @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_function( + self, + ) -> Callable[ + [functions.CreateFunctionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_function( + self, + ) -> Callable[ + [functions.UpdateFunctionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_function( + self, + ) -> Callable[ + [functions.DeleteFunctionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - Union[ - functions.GenerateUploadUrlResponse, - Awaitable[functions.GenerateUploadUrlResponse] - ]]: + def generate_upload_url( + self, + ) -> Callable[ + [functions.GenerateUploadUrlRequest], + Union[ + functions.GenerateUploadUrlResponse, + Awaitable[functions.GenerateUploadUrlResponse], + ], + ]: raise NotImplementedError() @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - Union[ - functions.GenerateDownloadUrlResponse, - Awaitable[functions.GenerateDownloadUrlResponse] - ]]: + def generate_download_url( + self, + ) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Union[ + functions.GenerateDownloadUrlResponse, + Awaitable[functions.GenerateDownloadUrlResponse], + ], + ]: raise NotImplementedError() @property - def list_runtimes(self) -> Callable[ - [functions.ListRuntimesRequest], - Union[ - functions.ListRuntimesResponse, - Awaitable[functions.ListRuntimesResponse] - ]]: + def list_runtimes( + self, + ) -> Callable[ + [functions.ListRuntimesRequest], + Union[ + functions.ListRuntimesResponse, Awaitable[functions.ListRuntimesResponse] + ], + ]: raise NotImplementedError() @property @@ -258,7 +274,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -302,10 +321,14 @@ def test_iam_permissions( raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -314,6 +337,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'FunctionServiceTransport', -) +__all__ = ("FunctionServiceTransport",) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py b/google/cloud/functions_v2/services/function_service/transports/grpc.py similarity index 82% rename from owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py rename to google/cloud/functions_v2/services/function_service/transports/grpc.py index 46f5af8..668762f 100644 --- a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py +++ b/google/cloud/functions_v2/services/function_service/transports/grpc.py @@ -13,25 +13,22 @@ # 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 +import warnings -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.api_core import gapic_v1, grpc_helpers, operations_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.functions_v2.types import functions -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore 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 from google.longrunning import operations_pb2 # type: ignore -from .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO +import grpc # type: ignore + +from google.cloud.functions_v2.types import functions + +from .base import DEFAULT_CLIENT_INFO, FunctionServiceTransport class FunctionServiceGrpcTransport(FunctionServiceTransport): @@ -51,23 +48,26 @@ class FunctionServiceGrpcTransport(FunctionServiceTransport): 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 = 'cloudfunctions.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, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "cloudfunctions.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, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -187,13 +187,15 @@ def __init__(self, *, self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'cloudfunctions.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: + def create_channel( + cls, + host: str = "cloudfunctions.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. @@ -228,13 +230,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -246,17 +247,15 @@ def operations_client(self) -> operations_v1.OperationsClient: """ # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) # Return the client from cache. return self._operations_client @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - functions.Function]: + def get_function( + self, + ) -> Callable[[functions.GetFunctionRequest], functions.Function]: r"""Return a callable for the get function method over gRPC. Returns a function with the given name from the @@ -272,18 +271,18 @@ def get_function(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_function' not in self._stubs: - self._stubs['get_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/GetFunction', + if "get_function" not in self._stubs: + self._stubs["get_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GetFunction", request_serializer=functions.GetFunctionRequest.serialize, response_deserializer=functions.Function.deserialize, ) - return self._stubs['get_function'] + return self._stubs["get_function"] @property - def list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - functions.ListFunctionsResponse]: + def list_functions( + self, + ) -> Callable[[functions.ListFunctionsRequest], functions.ListFunctionsResponse]: r"""Return a callable for the list functions method over gRPC. Returns a list of functions that belong to the @@ -299,18 +298,18 @@ def list_functions(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_functions' not in self._stubs: - self._stubs['list_functions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/ListFunctions', + if "list_functions" not in self._stubs: + self._stubs["list_functions"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/ListFunctions", request_serializer=functions.ListFunctionsRequest.serialize, response_deserializer=functions.ListFunctionsResponse.deserialize, ) - return self._stubs['list_functions'] + return self._stubs["list_functions"] @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - operations_pb2.Operation]: + def create_function( + self, + ) -> Callable[[functions.CreateFunctionRequest], operations_pb2.Operation]: r"""Return a callable for the create function method over gRPC. Creates a new function. If a function with the given name @@ -327,18 +326,18 @@ def create_function(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_function' not in self._stubs: - self._stubs['create_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/CreateFunction', + if "create_function" not in self._stubs: + self._stubs["create_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/CreateFunction", request_serializer=functions.CreateFunctionRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_function'] + return self._stubs["create_function"] @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - operations_pb2.Operation]: + def update_function( + self, + ) -> Callable[[functions.UpdateFunctionRequest], operations_pb2.Operation]: r"""Return a callable for the update function method over gRPC. Updates existing function. @@ -353,18 +352,18 @@ def update_function(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_function' not in self._stubs: - self._stubs['update_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/UpdateFunction', + if "update_function" not in self._stubs: + self._stubs["update_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/UpdateFunction", request_serializer=functions.UpdateFunctionRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_function'] + return self._stubs["update_function"] @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - operations_pb2.Operation]: + def delete_function( + self, + ) -> Callable[[functions.DeleteFunctionRequest], operations_pb2.Operation]: r"""Return a callable for the delete function method over gRPC. Deletes a function with the given name from the @@ -382,18 +381,20 @@ def delete_function(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_function' not in self._stubs: - self._stubs['delete_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/DeleteFunction', + if "delete_function" not in self._stubs: + self._stubs["delete_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/DeleteFunction", request_serializer=functions.DeleteFunctionRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_function'] + return self._stubs["delete_function"] @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - functions.GenerateUploadUrlResponse]: + def generate_upload_url( + self, + ) -> Callable[ + [functions.GenerateUploadUrlRequest], functions.GenerateUploadUrlResponse + ]: r"""Return a callable for the generate upload url method over gRPC. Returns a signed URL for uploading a function source code. For @@ -433,18 +434,20 @@ def generate_upload_url(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'generate_upload_url' not in self._stubs: - self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/GenerateUploadUrl', + if "generate_upload_url" not in self._stubs: + self._stubs["generate_upload_url"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GenerateUploadUrl", request_serializer=functions.GenerateUploadUrlRequest.serialize, response_deserializer=functions.GenerateUploadUrlResponse.deserialize, ) - return self._stubs['generate_upload_url'] + return self._stubs["generate_upload_url"] @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - functions.GenerateDownloadUrlResponse]: + def generate_download_url( + self, + ) -> Callable[ + [functions.GenerateDownloadUrlRequest], functions.GenerateDownloadUrlResponse + ]: r"""Return a callable for the generate download url method over gRPC. Returns a signed URL for downloading deployed @@ -464,18 +467,18 @@ def generate_download_url(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'generate_download_url' not in self._stubs: - self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/GenerateDownloadUrl', + if "generate_download_url" not in self._stubs: + self._stubs["generate_download_url"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GenerateDownloadUrl", request_serializer=functions.GenerateDownloadUrlRequest.serialize, response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, ) - return self._stubs['generate_download_url'] + return self._stubs["generate_download_url"] @property - def list_runtimes(self) -> Callable[ - [functions.ListRuntimesRequest], - functions.ListRuntimesResponse]: + def list_runtimes( + self, + ) -> Callable[[functions.ListRuntimesRequest], functions.ListRuntimesResponse]: r"""Return a callable for the list runtimes method over gRPC. Returns a list of runtimes that are supported for the @@ -491,13 +494,13 @@ def list_runtimes(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_runtimes' not in self._stubs: - self._stubs['list_runtimes'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/ListRuntimes', + if "list_runtimes" not in self._stubs: + self._stubs["list_runtimes"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/ListRuntimes", request_serializer=functions.ListRuntimesRequest.serialize, response_deserializer=functions.ListRuntimesResponse.deserialize, ) - return self._stubs['list_runtimes'] + return self._stubs["list_runtimes"] def close(self): self.grpc_channel.close() @@ -506,8 +509,7 @@ def close(self): def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -523,9 +525,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -541,9 +544,10 @@ def list_operations( @property def list_locations( self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -611,7 +615,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. Tests the specified permissions against the IAM access control @@ -640,6 +645,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'FunctionServiceGrpcTransport', -) +__all__ = ("FunctionServiceGrpcTransport",) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py b/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py similarity index 82% rename from owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py rename to google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py index a9bd369..013f594 100644 --- a/owl-bot-staging/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py +++ b/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py @@ -13,25 +13,22 @@ # 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 +import warnings -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.api_core import gapic_v1, grpc_helpers_async, 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.functions_v2.types import functions -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore 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 from google.longrunning import operations_pb2 # type: ignore -from .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.functions_v2.types import functions + +from .base import DEFAULT_CLIENT_INFO, FunctionServiceTransport from .grpc import FunctionServiceGrpcTransport @@ -57,13 +54,15 @@ class FunctionServiceGrpcAsyncIOTransport(FunctionServiceTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'cloudfunctions.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: + def create_channel( + cls, + host: str = "cloudfunctions.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. @@ -94,24 +93,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'cloudfunctions.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, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "cloudfunctions.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, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -257,9 +258,9 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - Awaitable[functions.Function]]: + def get_function( + self, + ) -> Callable[[functions.GetFunctionRequest], Awaitable[functions.Function]]: r"""Return a callable for the get function method over gRPC. Returns a function with the given name from the @@ -275,18 +276,20 @@ def get_function(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_function' not in self._stubs: - self._stubs['get_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/GetFunction', + if "get_function" not in self._stubs: + self._stubs["get_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GetFunction", request_serializer=functions.GetFunctionRequest.serialize, response_deserializer=functions.Function.deserialize, ) - return self._stubs['get_function'] + return self._stubs["get_function"] @property - def list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - Awaitable[functions.ListFunctionsResponse]]: + def list_functions( + self, + ) -> Callable[ + [functions.ListFunctionsRequest], Awaitable[functions.ListFunctionsResponse] + ]: r"""Return a callable for the list functions method over gRPC. Returns a list of functions that belong to the @@ -302,18 +305,20 @@ def list_functions(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_functions' not in self._stubs: - self._stubs['list_functions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/ListFunctions', + if "list_functions" not in self._stubs: + self._stubs["list_functions"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/ListFunctions", request_serializer=functions.ListFunctionsRequest.serialize, response_deserializer=functions.ListFunctionsResponse.deserialize, ) - return self._stubs['list_functions'] + return self._stubs["list_functions"] @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - Awaitable[operations_pb2.Operation]]: + def create_function( + self, + ) -> Callable[ + [functions.CreateFunctionRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the create function method over gRPC. Creates a new function. If a function with the given name @@ -330,18 +335,20 @@ def create_function(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_function' not in self._stubs: - self._stubs['create_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/CreateFunction', + if "create_function" not in self._stubs: + self._stubs["create_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/CreateFunction", request_serializer=functions.CreateFunctionRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_function'] + return self._stubs["create_function"] @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - Awaitable[operations_pb2.Operation]]: + def update_function( + self, + ) -> Callable[ + [functions.UpdateFunctionRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the update function method over gRPC. Updates existing function. @@ -356,18 +363,20 @@ def update_function(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_function' not in self._stubs: - self._stubs['update_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/UpdateFunction', + if "update_function" not in self._stubs: + self._stubs["update_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/UpdateFunction", request_serializer=functions.UpdateFunctionRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_function'] + return self._stubs["update_function"] @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - Awaitable[operations_pb2.Operation]]: + def delete_function( + self, + ) -> Callable[ + [functions.DeleteFunctionRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete function method over gRPC. Deletes a function with the given name from the @@ -385,18 +394,21 @@ def delete_function(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_function' not in self._stubs: - self._stubs['delete_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/DeleteFunction', + if "delete_function" not in self._stubs: + self._stubs["delete_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/DeleteFunction", request_serializer=functions.DeleteFunctionRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_function'] + return self._stubs["delete_function"] @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - Awaitable[functions.GenerateUploadUrlResponse]]: + def generate_upload_url( + self, + ) -> Callable[ + [functions.GenerateUploadUrlRequest], + Awaitable[functions.GenerateUploadUrlResponse], + ]: r"""Return a callable for the generate upload url method over gRPC. Returns a signed URL for uploading a function source code. For @@ -436,18 +448,21 @@ def generate_upload_url(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'generate_upload_url' not in self._stubs: - self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/GenerateUploadUrl', + if "generate_upload_url" not in self._stubs: + self._stubs["generate_upload_url"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GenerateUploadUrl", request_serializer=functions.GenerateUploadUrlRequest.serialize, response_deserializer=functions.GenerateUploadUrlResponse.deserialize, ) - return self._stubs['generate_upload_url'] + return self._stubs["generate_upload_url"] @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - Awaitable[functions.GenerateDownloadUrlResponse]]: + def generate_download_url( + self, + ) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Awaitable[functions.GenerateDownloadUrlResponse], + ]: r"""Return a callable for the generate download url method over gRPC. Returns a signed URL for downloading deployed @@ -467,18 +482,20 @@ def generate_download_url(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'generate_download_url' not in self._stubs: - self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/GenerateDownloadUrl', + if "generate_download_url" not in self._stubs: + self._stubs["generate_download_url"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GenerateDownloadUrl", request_serializer=functions.GenerateDownloadUrlRequest.serialize, response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, ) - return self._stubs['generate_download_url'] + return self._stubs["generate_download_url"] @property - def list_runtimes(self) -> Callable[ - [functions.ListRuntimesRequest], - Awaitable[functions.ListRuntimesResponse]]: + def list_runtimes( + self, + ) -> Callable[ + [functions.ListRuntimesRequest], Awaitable[functions.ListRuntimesResponse] + ]: r"""Return a callable for the list runtimes method over gRPC. Returns a list of runtimes that are supported for the @@ -494,13 +511,13 @@ def list_runtimes(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_runtimes' not in self._stubs: - self._stubs['list_runtimes'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v2.FunctionService/ListRuntimes', + if "list_runtimes" not in self._stubs: + self._stubs["list_runtimes"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/ListRuntimes", request_serializer=functions.ListRuntimesRequest.serialize, response_deserializer=functions.ListRuntimesResponse.deserialize, ) - return self._stubs['list_runtimes'] + return self._stubs["list_runtimes"] def close(self): return self.grpc_channel.close() @@ -509,8 +526,7 @@ def close(self): def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -526,9 +542,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -544,9 +561,10 @@ def list_operations( @property def list_locations( self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -614,7 +632,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. Tests the specified permissions against the IAM access control @@ -639,6 +658,4 @@ def test_iam_permissions( return self._stubs["test_iam_permissions"] -__all__ = ( - 'FunctionServiceGrpcAsyncIOTransport', -) +__all__ = ("FunctionServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/types/__init__.py b/google/cloud/functions_v2/types/__init__.py similarity index 65% rename from owl-bot-staging/v2/google/cloud/functions_v2/types/__init__.py rename to google/cloud/functions_v2/types/__init__.py index 33ebfca..82a10a9 100644 --- a/owl-bot-staging/v2/google/cloud/functions_v2/types/__init__.py +++ b/google/cloud/functions_v2/types/__init__.py @@ -17,6 +17,7 @@ BuildConfig, CreateFunctionRequest, DeleteFunctionRequest, + Environment, EventFilter, EventTrigger, Function, @@ -40,35 +41,34 @@ StateMessage, StorageSource, UpdateFunctionRequest, - Environment, ) __all__ = ( - 'BuildConfig', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventFilter', - 'EventTrigger', - 'Function', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'ListRuntimesRequest', - 'ListRuntimesResponse', - 'OperationMetadata', - 'RepoSource', - 'SecretEnvVar', - 'SecretVolume', - 'ServiceConfig', - 'Source', - 'SourceProvenance', - 'Stage', - 'StateMessage', - 'StorageSource', - 'UpdateFunctionRequest', - 'Environment', + "BuildConfig", + "CreateFunctionRequest", + "DeleteFunctionRequest", + "EventFilter", + "EventTrigger", + "Function", + "GenerateDownloadUrlRequest", + "GenerateDownloadUrlResponse", + "GenerateUploadUrlRequest", + "GenerateUploadUrlResponse", + "GetFunctionRequest", + "ListFunctionsRequest", + "ListFunctionsResponse", + "ListRuntimesRequest", + "ListRuntimesResponse", + "OperationMetadata", + "RepoSource", + "SecretEnvVar", + "SecretVolume", + "ServiceConfig", + "Source", + "SourceProvenance", + "Stage", + "StateMessage", + "StorageSource", + "UpdateFunctionRequest", + "Environment", ) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/types/functions.py b/google/cloud/functions_v2/types/functions.py similarity index 96% rename from owl-bot-staging/v2/google/cloud/functions_v2/types/functions.py rename to google/cloud/functions_v2/types/functions.py index 207cb88..04435fb 100644 --- a/owl-bot-staging/v2/google/cloud/functions_v2/types/functions.py +++ b/google/cloud/functions_v2/types/functions.py @@ -13,43 +13,41 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import proto # type: ignore - from google.protobuf import any_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.cloud.functions.v2', + package="google.cloud.functions.v2", manifest={ - 'Environment', - 'Function', - 'StateMessage', - 'StorageSource', - 'RepoSource', - 'Source', - 'SourceProvenance', - 'BuildConfig', - 'ServiceConfig', - 'SecretEnvVar', - 'SecretVolume', - 'EventTrigger', - 'EventFilter', - 'GetFunctionRequest', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'CreateFunctionRequest', - 'UpdateFunctionRequest', - 'DeleteFunctionRequest', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'ListRuntimesRequest', - 'ListRuntimesResponse', - 'OperationMetadata', - 'Stage', + "Environment", + "Function", + "StateMessage", + "StorageSource", + "RepoSource", + "Source", + "SourceProvenance", + "BuildConfig", + "ServiceConfig", + "SecretEnvVar", + "SecretVolume", + "EventTrigger", + "EventFilter", + "GetFunctionRequest", + "ListFunctionsRequest", + "ListFunctionsResponse", + "CreateFunctionRequest", + "UpdateFunctionRequest", + "DeleteFunctionRequest", + "GenerateUploadUrlRequest", + "GenerateUploadUrlResponse", + "GenerateDownloadUrlRequest", + "GenerateDownloadUrlResponse", + "ListRuntimesRequest", + "ListRuntimesResponse", + "OperationMetadata", + "Stage", }, ) @@ -98,6 +96,7 @@ class Function(proto.Message): Output only. State Messages for this Cloud Function. """ + class State(proto.Enum): r"""Describes the current state of the function.""" STATE_UNSPECIFIED = 0 @@ -114,7 +113,7 @@ class State(proto.Enum): environment = proto.Field( proto.ENUM, number=10, - enum='Environment', + enum="Environment", ) description = proto.Field( proto.STRING, @@ -123,17 +122,17 @@ class State(proto.Enum): build_config = proto.Field( proto.MESSAGE, number=3, - message='BuildConfig', + message="BuildConfig", ) service_config = proto.Field( proto.MESSAGE, number=4, - message='ServiceConfig', + message="ServiceConfig", ) event_trigger = proto.Field( proto.MESSAGE, number=5, - message='EventTrigger', + message="EventTrigger", ) state = proto.Field( proto.ENUM, @@ -153,7 +152,7 @@ class State(proto.Enum): state_messages = proto.RepeatedField( proto.MESSAGE, number=9, - message='StateMessage', + message="StateMessage", ) @@ -169,6 +168,7 @@ class StateMessage(proto.Message): message (str): The message. """ + class Severity(proto.Enum): r"""Severity of the state message.""" SEVERITY_UNSPECIFIED = 0 @@ -276,17 +276,17 @@ class RepoSource(proto.Message): branch_name = proto.Field( proto.STRING, number=3, - oneof='revision', + oneof="revision", ) tag_name = proto.Field( proto.STRING, number=4, - oneof='revision', + oneof="revision", ) commit_sha = proto.Field( proto.STRING, number=5, - oneof='revision', + oneof="revision", ) project_id = proto.Field( proto.STRING, @@ -332,14 +332,14 @@ class Source(proto.Message): storage_source = proto.Field( proto.MESSAGE, number=1, - oneof='source', - message='StorageSource', + oneof="source", + message="StorageSource", ) repo_source = proto.Field( proto.MESSAGE, number=2, - oneof='source', - message='RepoSource', + oneof="source", + message="RepoSource", ) @@ -359,12 +359,12 @@ class SourceProvenance(proto.Message): resolved_storage_source = proto.Field( proto.MESSAGE, number=1, - message='StorageSource', + message="StorageSource", ) resolved_repo_source = proto.Field( proto.MESSAGE, number=2, - message='RepoSource', + message="RepoSource", ) @@ -442,12 +442,12 @@ class BuildConfig(proto.Message): source = proto.Field( proto.MESSAGE, number=4, - message='Source', + message="Source", ) source_provenance = proto.Field( proto.MESSAGE, number=8, - message='SourceProvenance', + message="SourceProvenance", ) worker_pool = proto.Field( proto.STRING, @@ -547,6 +547,7 @@ class ServiceConfig(proto.Message): revision (str): Output only. The name of service revision. """ + class VpcConnectorEgressSettings(proto.Enum): r"""Available egress settings. @@ -623,12 +624,12 @@ class IngressSettings(proto.Enum): secret_environment_variables = proto.RepeatedField( proto.MESSAGE, number=17, - message='SecretEnvVar', + message="SecretEnvVar", ) secret_volumes = proto.RepeatedField( proto.MESSAGE, number=19, - message='SecretVolume', + message="SecretVolume", ) revision = proto.Field( proto.STRING, @@ -799,6 +800,7 @@ class EventTrigger(proto.Message): format. You must provide a channel to receive events from Eventarc SaaS partners. """ + class RetryPolicy(proto.Enum): r"""Describes the retry policy in case of function's execution failure. Retried execution is charged as any other execution. @@ -822,7 +824,7 @@ class RetryPolicy(proto.Enum): event_filters = proto.RepeatedField( proto.MESSAGE, number=4, - message='EventFilter', + message="EventFilter", ) pubsub_topic = proto.Field( proto.STRING, @@ -966,7 +968,7 @@ def raw_page(self): functions = proto.RepeatedField( proto.MESSAGE, number=1, - message='Function', + message="Function", ) next_page_token = proto.Field( proto.STRING, @@ -1003,7 +1005,7 @@ class CreateFunctionRequest(proto.Message): function = proto.Field( proto.MESSAGE, number=2, - message='Function', + message="Function", ) function_id = proto.Field( proto.STRING, @@ -1026,7 +1028,7 @@ class UpdateFunctionRequest(proto.Message): function = proto.Field( proto.MESSAGE, number=1, - message='Function', + message="Function", ) update_mask = proto.Field( proto.MESSAGE, @@ -1095,7 +1097,7 @@ class GenerateUploadUrlResponse(proto.Message): storage_source = proto.Field( proto.MESSAGE, number=2, - message='StorageSource', + message="StorageSource", ) @@ -1162,6 +1164,7 @@ class ListRuntimesResponse(proto.Message): runtimes (Sequence[google.cloud.functions_v2.types.ListRuntimesResponse.Runtime]): The runtimes that match the request. """ + class RuntimeStage(proto.Enum): r"""The various stages that a runtime can be in.""" RUNTIME_STAGE_UNSPECIFIED = 0 @@ -1204,7 +1207,7 @@ class Runtime(proto.Message): stage = proto.Field( proto.ENUM, number=2, - enum='ListRuntimesResponse.RuntimeStage', + enum="ListRuntimesResponse.RuntimeStage", ) warnings = proto.RepeatedField( proto.STRING, @@ -1213,7 +1216,7 @@ class Runtime(proto.Message): environment = proto.Field( proto.ENUM, number=4, - enum='Environment', + enum="Environment", ) runtimes = proto.RepeatedField( @@ -1292,7 +1295,7 @@ class OperationMetadata(proto.Message): stages = proto.RepeatedField( proto.MESSAGE, number=9, - message='Stage', + message="Stage", ) @@ -1314,6 +1317,7 @@ class Stage(proto.Message): state_messages (Sequence[google.cloud.functions_v2.types.StateMessage]): State messages from the current Stage. """ + class Name(proto.Enum): r"""Possible names for a Stage""" NAME_UNSPECIFIED = 0 @@ -1356,7 +1360,7 @@ class State(proto.Enum): state_messages = proto.RepeatedField( proto.MESSAGE, number=6, - message='StateMessage', + message="StateMessage", ) diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index ca93bdf..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/functions/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 deleted file mode 100644 index 29227d4..0000000 --- a/owl-bot-staging/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 9e8399a..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/functions *.py -recursive-include google/cloud/functions_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 533650a..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Functions 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 Functions API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 3464a12..0000000 --- a/owl-bot-staging/v1/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-functions 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-functions" -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-functions-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-functions.tex", - u"google-cloud-functions 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-functions", - u"Google Cloud Functions 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-functions", - u"google-cloud-functions Documentation", - author, - "google-cloud-functions", - "GAPIC library for Google Cloud Functions API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst b/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst deleted file mode 100644 index 36d0114..0000000 --- a/owl-bot-staging/v1/docs/functions_v1/cloud_functions_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CloudFunctionsService ---------------------------------------- - -.. automodule:: google.cloud.functions_v1.services.cloud_functions_service - :members: - :inherited-members: - -.. automodule:: google.cloud.functions_v1.services.cloud_functions_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/functions_v1/services.rst b/owl-bot-staging/v1/docs/functions_v1/services.rst deleted file mode 100644 index 89ae970..0000000 --- a/owl-bot-staging/v1/docs/functions_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Functions v1 API -========================================== -.. toctree:: - :maxdepth: 2 - - cloud_functions_service diff --git a/owl-bot-staging/v1/docs/functions_v1/types.rst b/owl-bot-staging/v1/docs/functions_v1/types.rst deleted file mode 100644 index bebdfe9..0000000 --- a/owl-bot-staging/v1/docs/functions_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Functions v1 API -======================================= - -.. automodule:: google.cloud.functions_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index dc30f6d..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - functions_v1/services - functions_v1/types diff --git a/owl-bot-staging/v1/google/cloud/functions/__init__.py b/owl-bot-staging/v1/google/cloud/functions/__init__.py deleted file mode 100644 index c34f3b0..0000000 --- a/owl-bot-staging/v1/google/cloud/functions/__init__.py +++ /dev/null @@ -1,67 +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.functions_v1.services.cloud_functions_service.client import CloudFunctionsServiceClient -from google.cloud.functions_v1.services.cloud_functions_service.async_client import CloudFunctionsServiceAsyncClient - -from google.cloud.functions_v1.types.functions import CallFunctionRequest -from google.cloud.functions_v1.types.functions import CallFunctionResponse -from google.cloud.functions_v1.types.functions import CloudFunction -from google.cloud.functions_v1.types.functions import CreateFunctionRequest -from google.cloud.functions_v1.types.functions import DeleteFunctionRequest -from google.cloud.functions_v1.types.functions import EventTrigger -from google.cloud.functions_v1.types.functions import FailurePolicy -from google.cloud.functions_v1.types.functions import GenerateDownloadUrlRequest -from google.cloud.functions_v1.types.functions import GenerateDownloadUrlResponse -from google.cloud.functions_v1.types.functions import GenerateUploadUrlRequest -from google.cloud.functions_v1.types.functions import GenerateUploadUrlResponse -from google.cloud.functions_v1.types.functions import GetFunctionRequest -from google.cloud.functions_v1.types.functions import HttpsTrigger -from google.cloud.functions_v1.types.functions import ListFunctionsRequest -from google.cloud.functions_v1.types.functions import ListFunctionsResponse -from google.cloud.functions_v1.types.functions import SecretEnvVar -from google.cloud.functions_v1.types.functions import SecretVolume -from google.cloud.functions_v1.types.functions import SourceRepository -from google.cloud.functions_v1.types.functions import UpdateFunctionRequest -from google.cloud.functions_v1.types.functions import CloudFunctionStatus -from google.cloud.functions_v1.types.operations import OperationMetadataV1 -from google.cloud.functions_v1.types.operations import OperationType - -__all__ = ('CloudFunctionsServiceClient', - 'CloudFunctionsServiceAsyncClient', - 'CallFunctionRequest', - 'CallFunctionResponse', - 'CloudFunction', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventTrigger', - 'FailurePolicy', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'HttpsTrigger', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'SecretEnvVar', - 'SecretVolume', - 'SourceRepository', - 'UpdateFunctionRequest', - 'CloudFunctionStatus', - 'OperationMetadataV1', - 'OperationType', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py deleted file mode 100644 index 87351c6..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/__init__.py +++ /dev/null @@ -1,68 +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.cloud_functions_service import CloudFunctionsServiceClient -from .services.cloud_functions_service import CloudFunctionsServiceAsyncClient - -from .types.functions import CallFunctionRequest -from .types.functions import CallFunctionResponse -from .types.functions import CloudFunction -from .types.functions import CreateFunctionRequest -from .types.functions import DeleteFunctionRequest -from .types.functions import EventTrigger -from .types.functions import FailurePolicy -from .types.functions import GenerateDownloadUrlRequest -from .types.functions import GenerateDownloadUrlResponse -from .types.functions import GenerateUploadUrlRequest -from .types.functions import GenerateUploadUrlResponse -from .types.functions import GetFunctionRequest -from .types.functions import HttpsTrigger -from .types.functions import ListFunctionsRequest -from .types.functions import ListFunctionsResponse -from .types.functions import SecretEnvVar -from .types.functions import SecretVolume -from .types.functions import SourceRepository -from .types.functions import UpdateFunctionRequest -from .types.functions import CloudFunctionStatus -from .types.operations import OperationMetadataV1 -from .types.operations import OperationType - -__all__ = ( - 'CloudFunctionsServiceAsyncClient', -'CallFunctionRequest', -'CallFunctionResponse', -'CloudFunction', -'CloudFunctionStatus', -'CloudFunctionsServiceClient', -'CreateFunctionRequest', -'DeleteFunctionRequest', -'EventTrigger', -'FailurePolicy', -'GenerateDownloadUrlRequest', -'GenerateDownloadUrlResponse', -'GenerateUploadUrlRequest', -'GenerateUploadUrlResponse', -'GetFunctionRequest', -'HttpsTrigger', -'ListFunctionsRequest', -'ListFunctionsResponse', -'OperationMetadataV1', -'OperationType', -'SecretEnvVar', -'SecretVolume', -'SourceRepository', -'UpdateFunctionRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json deleted file mode 100644 index 5745d05..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/gapic_metadata.json +++ /dev/null @@ -1,133 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.functions_v1", - "protoPackage": "google.cloud.functions.v1", - "schema": "1.0", - "services": { - "CloudFunctionsService": { - "clients": { - "grpc": { - "libraryClient": "CloudFunctionsServiceClient", - "rpcs": { - "CallFunction": { - "methods": [ - "call_function" - ] - }, - "CreateFunction": { - "methods": [ - "create_function" - ] - }, - "DeleteFunction": { - "methods": [ - "delete_function" - ] - }, - "GenerateDownloadUrl": { - "methods": [ - "generate_download_url" - ] - }, - "GenerateUploadUrl": { - "methods": [ - "generate_upload_url" - ] - }, - "GetFunction": { - "methods": [ - "get_function" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFunctions": { - "methods": [ - "list_functions" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFunction": { - "methods": [ - "update_function" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CloudFunctionsServiceAsyncClient", - "rpcs": { - "CallFunction": { - "methods": [ - "call_function" - ] - }, - "CreateFunction": { - "methods": [ - "create_function" - ] - }, - "DeleteFunction": { - "methods": [ - "delete_function" - ] - }, - "GenerateDownloadUrl": { - "methods": [ - "generate_download_url" - ] - }, - "GenerateUploadUrl": { - "methods": [ - "generate_upload_url" - ] - }, - "GetFunction": { - "methods": [ - "get_function" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFunctions": { - "methods": [ - "list_functions" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFunction": { - "methods": [ - "update_function" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/py.typed b/owl-bot-staging/v1/google/cloud/functions_v1/py.typed deleted file mode 100644 index 982ebb1..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py deleted file mode 100644 index d784dc7..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/__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 CloudFunctionsServiceClient -from .async_client import CloudFunctionsServiceAsyncClient - -__all__ = ( - 'CloudFunctionsServiceClient', - 'CloudFunctionsServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py deleted file mode 100644 index 3010041..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py +++ /dev/null @@ -1,1423 +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_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport -from .client import CloudFunctionsServiceClient - - -class CloudFunctionsServiceAsyncClient: - """A service that application uses to manipulate triggers and - functions. - """ - - _client: CloudFunctionsServiceClient - - DEFAULT_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT - - cloud_function_path = staticmethod(CloudFunctionsServiceClient.cloud_function_path) - parse_cloud_function_path = staticmethod(CloudFunctionsServiceClient.parse_cloud_function_path) - crypto_key_path = staticmethod(CloudFunctionsServiceClient.crypto_key_path) - parse_crypto_key_path = staticmethod(CloudFunctionsServiceClient.parse_crypto_key_path) - repository_path = staticmethod(CloudFunctionsServiceClient.repository_path) - parse_repository_path = staticmethod(CloudFunctionsServiceClient.parse_repository_path) - common_billing_account_path = staticmethod(CloudFunctionsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CloudFunctionsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CloudFunctionsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CloudFunctionsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CloudFunctionsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CloudFunctionsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CloudFunctionsServiceClient.common_project_path) - parse_common_project_path = staticmethod(CloudFunctionsServiceClient.parse_common_project_path) - common_location_path = staticmethod(CloudFunctionsServiceClient.common_location_path) - parse_common_location_path = staticmethod(CloudFunctionsServiceClient.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: - CloudFunctionsServiceAsyncClient: The constructed client. - """ - return CloudFunctionsServiceClient.from_service_account_info.__func__(CloudFunctionsServiceAsyncClient, 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: - CloudFunctionsServiceAsyncClient: The constructed client. - """ - return CloudFunctionsServiceClient.from_service_account_file.__func__(CloudFunctionsServiceAsyncClient, 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 CloudFunctionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CloudFunctionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CloudFunctionsServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CloudFunctionsServiceClient).get_transport_class, type(CloudFunctionsServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CloudFunctionsServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the cloud functions service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CloudFunctionsServiceTransport]): 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 = CloudFunctionsServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_functions(self, - request: Union[functions.ListFunctionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsAsyncPager: - r"""Returns a list of functions that belong to the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): - The request object. Request for the `ListFunctions` - 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager: - Response for the ListFunctions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = functions.ListFunctionsRequest(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.list_functions, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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.ListFunctionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_function(self, - request: Union[functions.GetFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CloudFunction: - r"""Returns a function with the given name from the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): - The request object. Request for the `GetFunction` - method. - name (:class:`str`): - Required. The name of the function - which details should be obtained. - - 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.functions_v1.types.CloudFunction: - Describes a Cloud Function that - contains user computation executed in - response to an event. It encapsulate - function and triggers configurations. - - """ - # 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 = functions.GetFunctionRequest(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_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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 create_function(self, - request: Union[functions.CreateFunctionRequest, dict] = None, - *, - location: str = None, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): - The request object. Request for the `CreateFunction` - method. - location (:class:`str`): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - function (:class:`google.cloud.functions_v1.types.CloudFunction`): - Required. Function to be created. - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([location, function]) - if request is 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 = functions.CreateFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if function is not None: - request.function = function - - # 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_function, - default_timeout=600.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(( - ("location", request.location), - )), - ) - - # 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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def update_function(self, - request: Union[functions.UpdateFunctionRequest, dict] = None, - *, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates existing function. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): - The request object. Request for the `UpdateFunction` - method. - function (:class:`google.cloud.functions_v1.types.CloudFunction`): - Required. New version of the - function. - - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([function]) - if request is 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 = functions.UpdateFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if function is not None: - request.function = function - - # 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_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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(( - ("function.name", request.function.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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def delete_function(self, - request: Union[functions.DeleteFunctionRequest, 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 function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): - The request object. Request for the `DeleteFunction` - method. - name (:class:`str`): - Required. The name of the function - which should be deleted. - - 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.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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 = functions.DeleteFunctionRequest(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_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.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, - empty_pb2.Empty, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def call_function(self, - request: Union[functions.CallFunctionRequest, dict] = None, - *, - name: str = None, - data: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CallFunctionResponse: - r"""Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = await client.call_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): - The request object. Request for the `CallFunction` - method. - name (:class:`str`): - Required. The name of the function to - be called. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (:class:`str`): - Required. Input to be passed to the - function. - - This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: - Response of CallFunction method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, data]) - if request is 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 = functions.CallFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.call_function, - default_timeout=600.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 generate_upload_url(self, - request: Union[functions.GenerateUploadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateUploadUrlResponse: - r"""Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = await client.generate_upload_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): - The request object. Request of `GenerateSourceUploadUrl` - 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.cloud.functions_v1.types.GenerateUploadUrlResponse: - Response of GenerateSourceUploadUrl method. - """ - # Create or coerce a protobuf request object. - request = functions.GenerateUploadUrlRequest(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.generate_upload_url, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def generate_download_url(self, - request: Union[functions.GenerateDownloadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateDownloadUrlResponse: - r"""Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - .. code-block:: python - - from google.cloud import functions_v1 - - async def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = await client.generate_download_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): - The request object. Request of `GenerateDownloadUrl` - 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: - Response of GenerateDownloadUrl method. - """ - # Create or coerce a protobuf request object. - request = functions.GenerateDownloadUrlRequest(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.generate_download_url, - 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 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 on the specified - function. Replaces any existing policy. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await 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 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"""Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await 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 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"""Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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) - - 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-functions", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CloudFunctionsServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py deleted file mode 100644 index 53c6f1a..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py +++ /dev/null @@ -1,1613 +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_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CloudFunctionsServiceGrpcTransport -from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport - - -class CloudFunctionsServiceClientMeta(type): - """Metaclass for the CloudFunctionsService 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[CloudFunctionsServiceTransport]] - _transport_registry["grpc"] = CloudFunctionsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CloudFunctionsServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CloudFunctionsServiceTransport]: - """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 CloudFunctionsServiceClient(metaclass=CloudFunctionsServiceClientMeta): - """A service that application uses to manipulate triggers and - functions. - """ - - @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 = "cloudfunctions.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: - CloudFunctionsServiceClient: 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: - CloudFunctionsServiceClient: 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) -> CloudFunctionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CloudFunctionsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def cloud_function_path(project: str,location: str,function: str,) -> str: - """Returns a fully-qualified cloud_function string.""" - return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) - - @staticmethod - def parse_cloud_function_path(path: str) -> Dict[str,str]: - """Parses a cloud_function path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?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 repository_path(project: str,location: str,repository: str,) -> str: - """Returns a fully-qualified repository string.""" - return "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) - - @staticmethod - def parse_repository_path(path: str) -> Dict[str,str]: - """Parses a repository path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/repositories/(?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, CloudFunctionsServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the cloud functions service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CloudFunctionsServiceTransport]): 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, CloudFunctionsServiceTransport): - # transport is a CloudFunctionsServiceTransport 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, - api_audience=client_options.api_audience, - ) - - def list_functions(self, - request: Union[functions.ListFunctionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsPager: - r"""Returns a list of functions that belong to the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]): - The request object. Request for the `ListFunctions` - 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.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager: - Response for the ListFunctions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a functions.ListFunctionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.ListFunctionsRequest): - request = functions.ListFunctionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_functions] - - # 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.ListFunctionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_function(self, - request: Union[functions.GetFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CloudFunction: - r"""Returns a function with the given name from the - requested project. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = client.get_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GetFunctionRequest, dict]): - The request object. Request for the `GetFunction` - method. - name (str): - Required. The name of the function - which details should be obtained. - - 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.functions_v1.types.CloudFunction: - Describes a Cloud Function that - contains user computation executed in - response to an event. It encapsulate - function and triggers configurations. - - """ - # 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 functions.GetFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.GetFunctionRequest): - request = functions.GetFunctionRequest(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_function] - - # 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 create_function(self, - request: Union[functions.CreateFunctionRequest, dict] = None, - *, - location: str = None, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]): - The request object. Request for the `CreateFunction` - method. - location (str): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - function (google.cloud.functions_v1.types.CloudFunction): - Required. Function to be created. - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([location, function]) - if request is 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 functions.CreateFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.CreateFunctionRequest): - request = functions.CreateFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if function is not None: - request.function = function - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_function] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("location", request.location), - )), - ) - - # 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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def update_function(self, - request: Union[functions.UpdateFunctionRequest, dict] = None, - *, - function: functions.CloudFunction = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates existing function. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]): - The request object. Request for the `UpdateFunction` - method. - function (google.cloud.functions_v1.types.CloudFunction): - Required. New version of the - function. - - This corresponds to the ``function`` 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.functions_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers configurations. - - """ - # 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([function]) - if request is 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 functions.UpdateFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.UpdateFunctionRequest): - request = functions.UpdateFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if function is not None: - request.function = function - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_function] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("function.name", request.function.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, - functions.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def delete_function(self, - request: Union[functions.DeleteFunctionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.DeleteFunctionRequest, dict]): - The request object. Request for the `DeleteFunction` - method. - name (str): - Required. The name of the function - which should be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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 functions.DeleteFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.DeleteFunctionRequest): - request = functions.DeleteFunctionRequest(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_function] - - # 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, - empty_pb2.Empty, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def call_function(self, - request: Union[functions.CallFunctionRequest, dict] = None, - *, - name: str = None, - data: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CallFunctionResponse: - r"""Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = client.call_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): - The request object. Request for the `CallFunction` - method. - name (str): - Required. The name of the function to - be called. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (str): - Required. Input to be passed to the - function. - - This corresponds to the ``data`` 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.functions_v1.types.CallFunctionResponse: - Response of CallFunction method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, data]) - if request is 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 functions.CallFunctionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.CallFunctionRequest): - request = functions.CallFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.call_function] - - # 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 generate_upload_url(self, - request: Union[functions.GenerateUploadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateUploadUrlResponse: - r"""Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = client.generate_upload_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]): - The request object. Request of `GenerateSourceUploadUrl` - 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.cloud.functions_v1.types.GenerateUploadUrlResponse: - Response of GenerateSourceUploadUrl method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a functions.GenerateUploadUrlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.GenerateUploadUrlRequest): - request = functions.GenerateUploadUrlRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_upload_url] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_download_url(self, - request: Union[functions.GenerateDownloadUrlRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.GenerateDownloadUrlResponse: - r"""Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - .. code-block:: python - - from google.cloud import functions_v1 - - def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = client.generate_download_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]): - The request object. Request of `GenerateDownloadUrl` - 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.cloud.functions_v1.types.GenerateDownloadUrlResponse: - Response of GenerateDownloadUrl method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a functions.GenerateDownloadUrlRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, functions.GenerateDownloadUrlRequest): - request = functions.GenerateDownloadUrlRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_download_url] - - # 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 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 on the specified - function. Replaces any existing policy. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 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"""Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 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"""Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - .. code-block:: python - - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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-functions", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CloudFunctionsServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py deleted file mode 100644 index f31d4f1..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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.functions_v1.types import functions - - -class ListFunctionsPager: - """A pager for iterating through ``list_functions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``functions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFunctions`` requests and continue to iterate - through the ``functions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` - 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[..., functions.ListFunctionsResponse], - request: functions.ListFunctionsRequest, - response: functions.ListFunctionsResponse, - *, - 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.functions_v1.types.ListFunctionsRequest): - The initial request object. - response (google.cloud.functions_v1.types.ListFunctionsResponse): - 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 = functions.ListFunctionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[functions.ListFunctionsResponse]: - 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[functions.CloudFunction]: - for page in self.pages: - yield from page.functions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFunctionsAsyncPager: - """A pager for iterating through ``list_functions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.functions_v1.types.ListFunctionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``functions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFunctions`` requests and continue to iterate - through the ``functions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.functions_v1.types.ListFunctionsResponse` - 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[functions.ListFunctionsResponse]], - request: functions.ListFunctionsRequest, - response: functions.ListFunctionsResponse, - *, - 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.functions_v1.types.ListFunctionsRequest): - The initial request object. - response (google.cloud.functions_v1.types.ListFunctionsResponse): - 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 = functions.ListFunctionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[functions.ListFunctionsResponse]: - 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[functions.CloudFunction]: - async def async_generator(): - async for page in self.pages: - for response in page.functions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py deleted file mode 100644 index ac1ba7e..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/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 CloudFunctionsServiceTransport -from .grpc import CloudFunctionsServiceGrpcTransport -from .grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CloudFunctionsServiceTransport]] -_transport_registry['grpc'] = CloudFunctionsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CloudFunctionsServiceGrpcAsyncIOTransport - -__all__ = ( - 'CloudFunctionsServiceTransport', - 'CloudFunctionsServiceGrpcTransport', - 'CloudFunctionsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py deleted file mode 100644 index 2d3352f..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py +++ /dev/null @@ -1,331 +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.functions_v1.types import functions -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-functions', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class CloudFunctionsServiceTransport(abc.ABC): - """Abstract transport class for CloudFunctionsService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'cloudfunctions.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, - api_audience: Optional[str] = None, - **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. - """ - - 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) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_functions: gapic_v1.method.wrap_method( - self.list_functions, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_function: gapic_v1.method.wrap_method( - self.get_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.create_function: gapic_v1.method.wrap_method( - self.create_function, - default_timeout=600.0, - client_info=client_info, - ), - self.update_function: gapic_v1.method.wrap_method( - self.update_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.delete_function: gapic_v1.method.wrap_method( - self.delete_function, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.call_function: gapic_v1.method.wrap_method( - self.call_function, - default_timeout=600.0, - client_info=client_info, - ), - self.generate_upload_url: gapic_v1.method.wrap_method( - self.generate_upload_url, - default_timeout=None, - client_info=client_info, - ), - self.generate_download_url: gapic_v1.method.wrap_method( - self.generate_download_url, - 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.get_iam_policy: gapic_v1.method.wrap_method( - self.get_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 list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - Union[ - functions.ListFunctionsResponse, - Awaitable[functions.ListFunctionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - Union[ - functions.CloudFunction, - Awaitable[functions.CloudFunction] - ]]: - raise NotImplementedError() - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - Union[ - functions.CallFunctionResponse, - Awaitable[functions.CallFunctionResponse] - ]]: - raise NotImplementedError() - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - Union[ - functions.GenerateUploadUrlResponse, - Awaitable[functions.GenerateUploadUrlResponse] - ]]: - raise NotImplementedError() - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - Union[ - functions.GenerateDownloadUrlResponse, - Awaitable[functions.GenerateDownloadUrlResponse] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CloudFunctionsServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py deleted file mode 100644 index 92c02c9..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py +++ /dev/null @@ -1,593 +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.functions_v1.types import functions -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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO - - -class CloudFunctionsServiceGrpcTransport(CloudFunctionsServiceTransport): - """gRPC backend transport for CloudFunctionsService. - - A service that application uses to manipulate triggers and - functions. - - 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 = 'cloudfunctions.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, - api_audience: Optional[str] = None, - ) -> 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, - api_audience=api_audience, - ) - - 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 = 'cloudfunctions.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 list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - functions.ListFunctionsResponse]: - r"""Return a callable for the list functions method over gRPC. - - Returns a list of functions that belong to the - requested project. - - Returns: - Callable[[~.ListFunctionsRequest], - ~.ListFunctionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_functions' not in self._stubs: - self._stubs['list_functions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', - request_serializer=functions.ListFunctionsRequest.serialize, - response_deserializer=functions.ListFunctionsResponse.deserialize, - ) - return self._stubs['list_functions'] - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - functions.CloudFunction]: - r"""Return a callable for the get function method over gRPC. - - Returns a function with the given name from the - requested project. - - Returns: - Callable[[~.GetFunctionRequest], - ~.CloudFunction]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_function' not in self._stubs: - self._stubs['get_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', - request_serializer=functions.GetFunctionRequest.serialize, - response_deserializer=functions.CloudFunction.deserialize, - ) - return self._stubs['get_function'] - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create function method over gRPC. - - Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - Returns: - Callable[[~.CreateFunctionRequest], - ~.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_function' not in self._stubs: - self._stubs['create_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', - request_serializer=functions.CreateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_function'] - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - operations_pb2.Operation]: - r"""Return a callable for the update function method over gRPC. - - Updates existing function. - - Returns: - Callable[[~.UpdateFunctionRequest], - ~.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_function' not in self._stubs: - self._stubs['update_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', - request_serializer=functions.UpdateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_function'] - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete function method over gRPC. - - Deletes a function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - Returns: - Callable[[~.DeleteFunctionRequest], - ~.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_function' not in self._stubs: - self._stubs['delete_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', - request_serializer=functions.DeleteFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_function'] - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - functions.CallFunctionResponse]: - r"""Return a callable for the call function method over gRPC. - - Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - Returns: - Callable[[~.CallFunctionRequest], - ~.CallFunctionResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'call_function' not in self._stubs: - self._stubs['call_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', - request_serializer=functions.CallFunctionRequest.serialize, - response_deserializer=functions.CallFunctionResponse.deserialize, - ) - return self._stubs['call_function'] - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - functions.GenerateUploadUrlResponse]: - r"""Return a callable for the generate upload url method over gRPC. - - Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - Returns: - Callable[[~.GenerateUploadUrlRequest], - ~.GenerateUploadUrlResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_upload_url' not in self._stubs: - self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', - request_serializer=functions.GenerateUploadUrlRequest.serialize, - response_deserializer=functions.GenerateUploadUrlResponse.deserialize, - ) - return self._stubs['generate_upload_url'] - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - functions.GenerateDownloadUrlResponse]: - r"""Return a callable for the generate download url method over gRPC. - - Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - Returns: - Callable[[~.GenerateDownloadUrlRequest], - ~.GenerateDownloadUrlResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_download_url' not in self._stubs: - self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', - request_serializer=functions.GenerateDownloadUrlRequest.serialize, - response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, - ) - return self._stubs['generate_download_url'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - r"""Return a callable for the test iam permissions method over gRPC. - - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/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__ = ( - 'CloudFunctionsServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py deleted file mode 100644 index d05047d..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,592 +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.functions_v1.types import functions -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 CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CloudFunctionsServiceGrpcTransport - - -class CloudFunctionsServiceGrpcAsyncIOTransport(CloudFunctionsServiceTransport): - """gRPC AsyncIO backend transport for CloudFunctionsService. - - A service that application uses to manipulate triggers and - functions. - - 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 = 'cloudfunctions.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 = 'cloudfunctions.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, - api_audience: Optional[str] = None, - ) -> 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, - api_audience=api_audience, - ) - - 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 list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - Awaitable[functions.ListFunctionsResponse]]: - r"""Return a callable for the list functions method over gRPC. - - Returns a list of functions that belong to the - requested project. - - Returns: - Callable[[~.ListFunctionsRequest], - Awaitable[~.ListFunctionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_functions' not in self._stubs: - self._stubs['list_functions'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/ListFunctions', - request_serializer=functions.ListFunctionsRequest.serialize, - response_deserializer=functions.ListFunctionsResponse.deserialize, - ) - return self._stubs['list_functions'] - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - Awaitable[functions.CloudFunction]]: - r"""Return a callable for the get function method over gRPC. - - Returns a function with the given name from the - requested project. - - Returns: - Callable[[~.GetFunctionRequest], - Awaitable[~.CloudFunction]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_function' not in self._stubs: - self._stubs['get_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GetFunction', - request_serializer=functions.GetFunctionRequest.serialize, - response_deserializer=functions.CloudFunction.deserialize, - ) - return self._stubs['get_function'] - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create function method over gRPC. - - Creates a new function. If a function with the given name - already exists in the specified project, the long running - operation will return ``ALREADY_EXISTS`` error. - - Returns: - Callable[[~.CreateFunctionRequest], - 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_function' not in self._stubs: - self._stubs['create_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CreateFunction', - request_serializer=functions.CreateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_function'] - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update function method over gRPC. - - Updates existing function. - - Returns: - Callable[[~.UpdateFunctionRequest], - 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_function' not in self._stubs: - self._stubs['update_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/UpdateFunction', - request_serializer=functions.UpdateFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_function'] - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete function method over gRPC. - - Deletes a function with the given name from the - specified project. If the given function is used by some - trigger, the trigger will be updated to remove this - function. - - Returns: - Callable[[~.DeleteFunctionRequest], - 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_function' not in self._stubs: - self._stubs['delete_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/DeleteFunction', - request_serializer=functions.DeleteFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_function'] - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - Awaitable[functions.CallFunctionResponse]]: - r"""Return a callable for the call function method over gRPC. - - Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - Returns: - Callable[[~.CallFunctionRequest], - Awaitable[~.CallFunctionResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'call_function' not in self._stubs: - self._stubs['call_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', - request_serializer=functions.CallFunctionRequest.serialize, - response_deserializer=functions.CallFunctionResponse.deserialize, - ) - return self._stubs['call_function'] - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - Awaitable[functions.GenerateUploadUrlResponse]]: - r"""Return a callable for the generate upload url method over gRPC. - - Returns a signed URL for uploading a function source code. For - more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls. - Once the function source code upload is complete, the used - signed URL should be provided in CreateFunction or - UpdateFunction request as a reference to the function source - code. - - When uploading source code to the generated signed URL, please - follow these restrictions: - - - Source file type should be a zip file. - - Source file size should not exceed 100MB limit. - - No credentials should be attached - the signed URLs provide - access to the target bucket using internal service identity; - if credentials were attached, the identity from the - credentials would be used, but that identity does not have - permissions to upload files to the URL. - - When making a HTTP PUT request, these two headers need to be - specified: - - - ``content-type: application/zip`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - Returns: - Callable[[~.GenerateUploadUrlRequest], - Awaitable[~.GenerateUploadUrlResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_upload_url' not in self._stubs: - self._stubs['generate_upload_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateUploadUrl', - request_serializer=functions.GenerateUploadUrlRequest.serialize, - response_deserializer=functions.GenerateUploadUrlResponse.deserialize, - ) - return self._stubs['generate_upload_url'] - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - Awaitable[functions.GenerateDownloadUrlResponse]]: - r"""Return a callable for the generate download url method over gRPC. - - Returns a signed URL for downloading deployed - function source code. The URL is only valid for a - limited period and should be used within minutes after - generation. - For more information about the signed URL usage see: - https://cloud.google.com/storage/docs/access-control/signed-urls - - Returns: - Callable[[~.GenerateDownloadUrlRequest], - Awaitable[~.GenerateDownloadUrlResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_download_url' not in self._stubs: - self._stubs['generate_download_url'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/GenerateDownloadUrl', - request_serializer=functions.GenerateDownloadUrlRequest.serialize, - response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, - ) - return self._stubs['generate_download_url'] - - @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 on the specified - function. Replaces 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.functions.v1.CloudFunctionsService/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - - Returns: - Callable[[~.GetIamPolicyRequest], - 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.functions.v1.CloudFunctionsService/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Returns: - Callable[[~.TestIamPermissionsRequest], - 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.functions.v1.CloudFunctionsService/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__ = ( - 'CloudFunctionsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py deleted file mode 100644 index b09e206..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/types/__init__.py +++ /dev/null @@ -1,66 +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 .functions import ( - CallFunctionRequest, - CallFunctionResponse, - CloudFunction, - CreateFunctionRequest, - DeleteFunctionRequest, - EventTrigger, - FailurePolicy, - GenerateDownloadUrlRequest, - GenerateDownloadUrlResponse, - GenerateUploadUrlRequest, - GenerateUploadUrlResponse, - GetFunctionRequest, - HttpsTrigger, - ListFunctionsRequest, - ListFunctionsResponse, - SecretEnvVar, - SecretVolume, - SourceRepository, - UpdateFunctionRequest, - CloudFunctionStatus, -) -from .operations import ( - OperationMetadataV1, - OperationType, -) - -__all__ = ( - 'CallFunctionRequest', - 'CallFunctionResponse', - 'CloudFunction', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventTrigger', - 'FailurePolicy', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'HttpsTrigger', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'SecretEnvVar', - 'SecretVolume', - 'SourceRepository', - 'UpdateFunctionRequest', - 'CloudFunctionStatus', - 'OperationMetadataV1', - 'OperationType', -) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py deleted file mode 100644 index 844c961..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/types/functions.py +++ /dev/null @@ -1,1067 +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 duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.functions.v1', - manifest={ - 'CloudFunctionStatus', - 'CloudFunction', - 'SourceRepository', - 'HttpsTrigger', - 'EventTrigger', - 'FailurePolicy', - 'SecretEnvVar', - 'SecretVolume', - 'CreateFunctionRequest', - 'UpdateFunctionRequest', - 'GetFunctionRequest', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'DeleteFunctionRequest', - 'CallFunctionRequest', - 'CallFunctionResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - }, -) - - -class CloudFunctionStatus(proto.Enum): - r"""Describes the current stage of a deployment.""" - CLOUD_FUNCTION_STATUS_UNSPECIFIED = 0 - ACTIVE = 1 - OFFLINE = 2 - DEPLOY_IN_PROGRESS = 3 - DELETE_IN_PROGRESS = 4 - UNKNOWN = 5 - - -class CloudFunction(proto.Message): - r"""Describes a Cloud Function that contains user computation - executed in response to an event. It encapsulate function and - triggers configurations. - - 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): - A user-defined name of the function. Function names must be - unique globally and match pattern - ``projects/*/locations/*/functions/*`` - description (str): - User-provided description of a function. - source_archive_url (str): - The Google Cloud Storage URL, starting with ``gs://``, - pointing to the zip archive which contains the function. - - This field is a member of `oneof`_ ``source_code``. - source_repository (google.cloud.functions_v1.types.SourceRepository): - **Beta Feature** - - The source repository where a function is hosted. - - This field is a member of `oneof`_ ``source_code``. - source_upload_url (str): - The Google Cloud Storage signed URL used for source - uploading, generated by calling - [google.cloud.functions.v1.GenerateUploadUrl]. - - The signature is validated on write methods (Create, Update) - The signature is stripped from the Function object on read - methods (Get, List) - - This field is a member of `oneof`_ ``source_code``. - https_trigger (google.cloud.functions_v1.types.HttpsTrigger): - An HTTPS endpoint type of source that can be - triggered via URL. - - This field is a member of `oneof`_ ``trigger``. - event_trigger (google.cloud.functions_v1.types.EventTrigger): - A source that fires events in response to a - condition in another service. - - This field is a member of `oneof`_ ``trigger``. - status (google.cloud.functions_v1.types.CloudFunctionStatus): - Output only. Status of the function - deployment. - entry_point (str): - The name of the function (as defined in source code) that - will be executed. Defaults to the resource name suffix, if - not specified. For backward compatibility, if function with - given name is not found, then the system will try to use - function named "function". For Node.js this is name of a - function exported by the module specified in - ``source_location``. - runtime (str): - The runtime in which to run the function. Required when - deploying a new function, optional when updating an existing - function. For a complete list of possible choices, see the - ```gcloud`` command - reference `__. - timeout (google.protobuf.duration_pb2.Duration): - The function execution timeout. Execution is - considered failed and can be terminated if the - function is not completed at the end of the - timeout period. Defaults to 60 seconds. - available_memory_mb (int): - The amount of memory in MB available for a - function. Defaults to 256MB. - service_account_email (str): - The email of the function's service account. If empty, - defaults to ``{project_id}@appspot.gserviceaccount.com``. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last update timestamp of a - Cloud Function. - version_id (int): - Output only. The version identifier of the - Cloud Function. Each deployment attempt results - in a new version of a function being created. - labels (Mapping[str, str]): - Labels associated with this Cloud Function. - environment_variables (Mapping[str, str]): - Environment variables that shall be available - during function execution. - build_environment_variables (Mapping[str, str]): - Build environment variables that shall be - available during build time. - network (str): - The VPC Network that this cloud function can connect to. It - can be either the fully-qualified URI, or the short name of - the network resource. If the short network name is used, the - network must belong to the same project. Otherwise, it must - belong to a project within the same organization. The format - of this field is either - ``projects/{project}/global/networks/{network}`` or - ``{network}``, where ``{project}`` is a project id where the - network is defined, and ``{network}`` is the short name of - the network. - - This field is mutually exclusive with ``vpc_connector`` and - will be replaced by it. - - See `the VPC - documentation `__ - for more information on connecting Cloud projects. - max_instances (int): - The limit on the maximum number of function instances that - may coexist at a given time. - - In some cases, such as rapid traffic surges, Cloud Functions - may, for a short period of time, create more instances than - the specified max instances limit. If your function cannot - tolerate this temporary behavior, you may want to factor in - a safety margin and set a lower max instances value than - your function can tolerate. - - See the `Max - Instances `__ - Guide for more details. - min_instances (int): - A lower bound for the number function - instances that may coexist at a given time. - vpc_connector (str): - The VPC Network Connector that this cloud function can - connect to. It can be either the fully-qualified URI, or the - short name of the network connector resource. The format of - this field is ``projects/*/locations/*/connectors/*`` - - This field is mutually exclusive with ``network`` field and - will eventually replace it. - - See `the VPC - documentation `__ - for more information on connecting Cloud projects. - vpc_connector_egress_settings (google.cloud.functions_v1.types.CloudFunction.VpcConnectorEgressSettings): - The egress settings for the connector, - controlling what traffic is diverted through it. - ingress_settings (google.cloud.functions_v1.types.CloudFunction.IngressSettings): - The ingress settings for the function, - controlling what traffic can reach it. - kms_key_name (str): - Resource name of a KMS crypto key (managed by the user) used - to encrypt/decrypt function resources. - - It must match the pattern - ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. - - If specified, you must also provide an artifact registry - repository using the ``docker_repository`` field that was - created with the same KMS crypto key. - - The following service accounts need to be granted the role - 'Cloud KMS CryptoKey Encrypter/Decrypter - (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the - Key/KeyRing/Project/Organization (least access preferred). - - 1. Google Cloud Functions service account - (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - - Required to protect the function's image. - 2. Google Storage service account - (service-{project_number}@gs-project-accounts.iam.gserviceaccount.com) - - Required to protect the function's source code. If this - service account does not exist, deploying a function - without a KMS key or retrieving the service agent name - provisions it. For more information, see - https://cloud.google.com/storage/docs/projects#service-agents - and - https://cloud.google.com/storage/docs/getting-service-agent#gsutil. - - Google Cloud Functions delegates access to service agents to - protect function resources in internal projects that are not - accessible by the end user. - build_worker_pool (str): - Name of the Cloud Build Custom Worker Pool that should be - used to build the function. The format of this field is - ``projects/{project}/locations/{region}/workerPools/{workerPool}`` - where ``{project}`` and ``{region}`` are the project id and - region respectively where the worker pool is defined and - ``{workerPool}`` is the short name of the worker pool. - - If the project id is not the same as the function, then the - Cloud Functions Service Agent - (``service-@gcf-admin-robot.iam.gserviceaccount.com``) - must be granted the role Cloud Build Custom Workers Builder - (``roles/cloudbuild.customworkers.builder``) in the project. - build_id (str): - Output only. The Cloud Build ID of the latest - successful deployment of the function. - build_name (str): - Output only. The Cloud Build Name of the function - deployment. - ``projects//locations//builds/``. - secret_environment_variables (Sequence[google.cloud.functions_v1.types.SecretEnvVar]): - Secret environment variables configuration. - secret_volumes (Sequence[google.cloud.functions_v1.types.SecretVolume]): - Secret volumes configuration. - source_token (str): - Input only. An identifier for Firebase - function sources. Disclaimer: This field is only - supported for Firebase function deployments. - docker_repository (str): - User managed repository created in Artifact Registry - optionally with a customer managed encryption key. If - specified, deployments will use Artifact Registry. If - unspecified and the deployment is eligible to use Artifact - Registry, GCF will create and use a repository named - 'gcf-artifacts' for every deployed region. This is the - repository to which the function docker image will be pushed - after it is built by Cloud Build. - - It must match the pattern - ``projects/{project}/locations/{location}/repositories/{repository}``. - - Cross-project repositories are not supported. Cross-location - repositories are not supported. Repository format must be - 'DOCKER'. - docker_registry (google.cloud.functions_v1.types.CloudFunction.DockerRegistry): - Docker Registry to use for this deployment. - - If ``docker_repository`` field is specified, this field will - be automatically set as ``ARTIFACT_REGISTRY``. If - unspecified, it currently defaults to - ``CONTAINER_REGISTRY``. This field may be overridden by the - backend for eligible deployments. - """ - class VpcConnectorEgressSettings(proto.Enum): - r"""Available egress settings. - - This controls what traffic is diverted through the VPC Access - Connector resource. By default PRIVATE_RANGES_ONLY will be used. - """ - VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED = 0 - PRIVATE_RANGES_ONLY = 1 - ALL_TRAFFIC = 2 - - class IngressSettings(proto.Enum): - r"""Available ingress settings. - - This controls what traffic can reach the function. - - If unspecified, ALLOW_ALL will be used. - """ - INGRESS_SETTINGS_UNSPECIFIED = 0 - ALLOW_ALL = 1 - ALLOW_INTERNAL_ONLY = 2 - ALLOW_INTERNAL_AND_GCLB = 3 - - class DockerRegistry(proto.Enum): - r"""Docker Registry to use for storing function Docker images.""" - DOCKER_REGISTRY_UNSPECIFIED = 0 - CONTAINER_REGISTRY = 1 - ARTIFACT_REGISTRY = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - source_archive_url = proto.Field( - proto.STRING, - number=3, - oneof='source_code', - ) - source_repository = proto.Field( - proto.MESSAGE, - number=4, - oneof='source_code', - message='SourceRepository', - ) - source_upload_url = proto.Field( - proto.STRING, - number=16, - oneof='source_code', - ) - https_trigger = proto.Field( - proto.MESSAGE, - number=5, - oneof='trigger', - message='HttpsTrigger', - ) - event_trigger = proto.Field( - proto.MESSAGE, - number=6, - oneof='trigger', - message='EventTrigger', - ) - status = proto.Field( - proto.ENUM, - number=7, - enum='CloudFunctionStatus', - ) - entry_point = proto.Field( - proto.STRING, - number=8, - ) - runtime = proto.Field( - proto.STRING, - number=19, - ) - timeout = proto.Field( - proto.MESSAGE, - number=9, - message=duration_pb2.Duration, - ) - available_memory_mb = proto.Field( - proto.INT32, - number=10, - ) - service_account_email = proto.Field( - proto.STRING, - number=11, - ) - update_time = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - version_id = proto.Field( - proto.INT64, - number=14, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=15, - ) - environment_variables = proto.MapField( - proto.STRING, - proto.STRING, - number=17, - ) - build_environment_variables = proto.MapField( - proto.STRING, - proto.STRING, - number=28, - ) - network = proto.Field( - proto.STRING, - number=18, - ) - max_instances = proto.Field( - proto.INT32, - number=20, - ) - min_instances = proto.Field( - proto.INT32, - number=32, - ) - vpc_connector = proto.Field( - proto.STRING, - number=22, - ) - vpc_connector_egress_settings = proto.Field( - proto.ENUM, - number=23, - enum=VpcConnectorEgressSettings, - ) - ingress_settings = proto.Field( - proto.ENUM, - number=24, - enum=IngressSettings, - ) - kms_key_name = proto.Field( - proto.STRING, - number=25, - ) - build_worker_pool = proto.Field( - proto.STRING, - number=26, - ) - build_id = proto.Field( - proto.STRING, - number=27, - ) - build_name = proto.Field( - proto.STRING, - number=33, - ) - secret_environment_variables = proto.RepeatedField( - proto.MESSAGE, - number=29, - message='SecretEnvVar', - ) - secret_volumes = proto.RepeatedField( - proto.MESSAGE, - number=30, - message='SecretVolume', - ) - source_token = proto.Field( - proto.STRING, - number=31, - ) - docker_repository = proto.Field( - proto.STRING, - number=34, - ) - docker_registry = proto.Field( - proto.ENUM, - number=35, - enum=DockerRegistry, - ) - - -class SourceRepository(proto.Message): - r"""Describes SourceRepository, used to represent parameters - related to source repository where a function is hosted. - - Attributes: - url (str): - The URL pointing to the hosted repository where the function - is defined. There are supported Cloud Source Repository URLs - in the following formats: - - To refer to a specific commit: - ``https://source.developers.google.com/projects/*/repos/*/revisions/*/paths/*`` - To refer to a moveable alias (branch): - ``https://source.developers.google.com/projects/*/repos/*/moveable-aliases/*/paths/*`` - In particular, to refer to HEAD use ``master`` moveable - alias. To refer to a specific fixed alias (tag): - ``https://source.developers.google.com/projects/*/repos/*/fixed-aliases/*/paths/*`` - - You may omit ``paths/*`` if you want to use the main - directory. - deployed_url (str): - Output only. The URL pointing to the hosted - repository where the function were defined at - the time of deployment. It always points to a - specific commit in the format described above. - """ - - url = proto.Field( - proto.STRING, - number=1, - ) - deployed_url = proto.Field( - proto.STRING, - number=2, - ) - - -class HttpsTrigger(proto.Message): - r"""Describes HttpsTrigger, could be used to connect web hooks to - function. - - Attributes: - url (str): - Output only. The deployed url for the - function. - security_level (google.cloud.functions_v1.types.HttpsTrigger.SecurityLevel): - The security level for the function. - """ - class SecurityLevel(proto.Enum): - r"""Available security level settings. - - This controls the methods to enforce security (HTTPS) on a URL. - - If unspecified, SECURE_OPTIONAL will be used. - """ - SECURITY_LEVEL_UNSPECIFIED = 0 - SECURE_ALWAYS = 1 - SECURE_OPTIONAL = 2 - - url = proto.Field( - proto.STRING, - number=1, - ) - security_level = proto.Field( - proto.ENUM, - number=2, - enum=SecurityLevel, - ) - - -class EventTrigger(proto.Message): - r"""Describes EventTrigger, used to request events be sent from - another service. - - Attributes: - event_type (str): - Required. The type of event to observe. For example: - ``providers/cloud.storage/eventTypes/object.change`` and - ``providers/cloud.pubsub/eventTypes/topic.publish``. - - Event types match pattern ``providers/*/eventTypes/*.*``. - The pattern contains: - - 1. namespace: For example, ``cloud.storage`` and - ``google.firebase.analytics``. - 2. resource type: The type of resource on which event - occurs. For example, the Google Cloud Storage API - includes the type ``object``. - 3. action: The action that generates the event. For example, - action for a Google Cloud Storage Object is 'change'. - These parts are lower case. - resource (str): - Required. The resource(s) from which to observe events, for - example, ``projects/_/buckets/myBucket``. - - Not all syntactically correct values are accepted by all - services. For example: - - 1. The authorization model must support it. Google Cloud - Functions only allows EventTriggers to be deployed that - observe resources in the same project as the - ``CloudFunction``. - 2. The resource type must match the pattern expected for an - ``event_type``. For example, an ``EventTrigger`` that has - an ``event_type`` of "google.pubsub.topic.publish" should - have a resource that matches Google Cloud Pub/Sub topics. - - Additionally, some services may support short names when - creating an ``EventTrigger``. These will always be returned - in the normalized "long" format. - - See each *service's* documentation for supported formats. - service (str): - The hostname of the service that should be observed. - - If no string is provided, the default service implementing - the API will be used. For example, - ``storage.googleapis.com`` is the default for all event - types in the ``google.storage`` namespace. - failure_policy (google.cloud.functions_v1.types.FailurePolicy): - Specifies policy for failed executions. - """ - - event_type = proto.Field( - proto.STRING, - number=1, - ) - resource = proto.Field( - proto.STRING, - number=2, - ) - service = proto.Field( - proto.STRING, - number=3, - ) - failure_policy = proto.Field( - proto.MESSAGE, - number=5, - message='FailurePolicy', - ) - - -class FailurePolicy(proto.Message): - r"""Describes the policy in case of function's execution failure. - If empty, then defaults to ignoring failures (i.e. not retrying - them). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - retry (google.cloud.functions_v1.types.FailurePolicy.Retry): - If specified, then the function will be - retried in case of a failure. - - This field is a member of `oneof`_ ``action``. - """ - - class Retry(proto.Message): - r"""Describes the retry policy in case of function's execution - failure. A function execution will be retried on any failure. A - failed execution will be retried up to 7 days with an - exponential backoff (capped at 10 seconds). - Retried execution is charged as any other execution. - - """ - - retry = proto.Field( - proto.MESSAGE, - number=1, - oneof='action', - message=Retry, - ) - - -class SecretEnvVar(proto.Message): - r"""Configuration for a secret environment variable. It has the - information necessary to fetch the secret value from secret - manager and expose it as an environment variable. - - Attributes: - key (str): - Name of the environment variable. - project_id (str): - Project identifier (preferrably project - number but can also be the project ID) of the - project that contains the secret. If not set, it - will be populated with the function's project - assuming that the secret exists in the same - project as of the function. - secret (str): - Name of the secret in secret manager (not the - full resource name). - version (str): - Version of the secret (version number or the - string 'latest'). It is recommended to use a - numeric version for secret environment variables - as any updates to the secret value is not - reflected until new instances start. - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - project_id = proto.Field( - proto.STRING, - number=2, - ) - secret = proto.Field( - proto.STRING, - number=3, - ) - version = proto.Field( - proto.STRING, - number=4, - ) - - -class SecretVolume(proto.Message): - r"""Configuration for a secret volume. It has the information - necessary to fetch the secret value from secret manager and make - it available as files mounted at the requested paths within the - application container. Secret value is not a part of the - configuration. Every filesystem read operation performs a lookup - in secret manager to retrieve the secret value. - - Attributes: - mount_path (str): - The path within the container to mount the secret volume. - For example, setting the mount_path as ``/etc/secrets`` - would mount the secret value files under the - ``/etc/secrets`` directory. This directory will also be - completely shadowed and unavailable to mount any other - secrets. - - Recommended mount paths: /etc/secrets Restricted mount - paths: /cloudsql, /dev/log, /pod, /proc, /var/log - project_id (str): - Project identifier (preferrably project - number but can also be the project ID) of the - project that contains the secret. If not set, it - will be populated with the function's project - assuming that the secret exists in the same - project as of the function. - secret (str): - Name of the secret in secret manager (not the - full resource name). - versions (Sequence[google.cloud.functions_v1.types.SecretVolume.SecretVersion]): - List of secret versions to mount for this secret. If empty, - the ``latest`` version of the secret will be made available - in a file named after the secret under the mount point. - """ - - class SecretVersion(proto.Message): - r"""Configuration for a single version. - - Attributes: - version (str): - Version of the secret (version number or the string - 'latest'). It is preferrable to use ``latest`` version with - secret volumes as secret value changes are reflected - immediately. - path (str): - Relative path of the file under the mount path where the - secret value for this version will be fetched and made - available. For example, setting the mount_path as - '/etc/secrets' and path as ``/secret_foo`` would mount the - secret value file at ``/etc/secrets/secret_foo``. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - path = proto.Field( - proto.STRING, - number=2, - ) - - mount_path = proto.Field( - proto.STRING, - number=1, - ) - project_id = proto.Field( - proto.STRING, - number=2, - ) - secret = proto.Field( - proto.STRING, - number=3, - ) - versions = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=SecretVersion, - ) - - -class CreateFunctionRequest(proto.Message): - r"""Request for the ``CreateFunction`` method. - - Attributes: - location (str): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - function (google.cloud.functions_v1.types.CloudFunction): - Required. Function to be created. - """ - - location = proto.Field( - proto.STRING, - number=1, - ) - function = proto.Field( - proto.MESSAGE, - number=2, - message='CloudFunction', - ) - - -class UpdateFunctionRequest(proto.Message): - r"""Request for the ``UpdateFunction`` method. - - Attributes: - function (google.cloud.functions_v1.types.CloudFunction): - Required. New version of the function. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields in ``CloudFunction`` that have - to be updated. - """ - - function = proto.Field( - proto.MESSAGE, - number=1, - message='CloudFunction', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetFunctionRequest(proto.Message): - r"""Request for the ``GetFunction`` method. - - Attributes: - name (str): - Required. The name of the function which - details should be obtained. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFunctionsRequest(proto.Message): - r"""Request for the ``ListFunctions`` method. - - Attributes: - parent (str): - The project and location from which the function should be - listed, specified in the format ``projects/*/locations/*`` - If you want to list functions in all locations, use "-" in - place of a location. When listing functions in all - locations, if one or more location(s) are unreachable, the - response will contain functions from all reachable locations - along with the names of any unreachable locations. - page_size (int): - Maximum number of functions to return per - call. - page_token (str): - The value returned by the last ``ListFunctionsResponse``; - indicates that this is a continuation of a prior - ``ListFunctions`` call, and that the system should return - the next page of data. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListFunctionsResponse(proto.Message): - r"""Response for the ``ListFunctions`` method. - - Attributes: - functions (Sequence[google.cloud.functions_v1.types.CloudFunction]): - The functions that match the request. - next_page_token (str): - If not empty, indicates that there may be more functions - that match the request; this value should be passed in a new - [google.cloud.functions.v1.ListFunctionsRequest][google.cloud.functions.v1.ListFunctionsRequest] - to get more functions. - unreachable (Sequence[str]): - Locations that could not be reached. The - response does not include any functions from - these locations. - """ - - @property - def raw_page(self): - return self - - functions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='CloudFunction', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - unreachable = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class DeleteFunctionRequest(proto.Message): - r"""Request for the ``DeleteFunction`` method. - - Attributes: - name (str): - Required. The name of the function which - should be deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CallFunctionRequest(proto.Message): - r"""Request for the ``CallFunction`` method. - - Attributes: - name (str): - Required. The name of the function to be - called. - data (str): - Required. Input to be passed to the function. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - data = proto.Field( - proto.STRING, - number=2, - ) - - -class CallFunctionResponse(proto.Message): - r"""Response of ``CallFunction`` method. - - Attributes: - execution_id (str): - Execution id of function invocation. - result (str): - Result populated for successful execution of - synchronous function. Will not be populated if - function does not return a result through - context. - error (str): - Either system or user-function generated - error. Set if execution was not successful. - """ - - execution_id = proto.Field( - proto.STRING, - number=1, - ) - result = proto.Field( - proto.STRING, - number=2, - ) - error = proto.Field( - proto.STRING, - number=3, - ) - - -class GenerateUploadUrlRequest(proto.Message): - r"""Request of ``GenerateSourceUploadUrl`` method. - - Attributes: - parent (str): - The project and location in which the Google Cloud Storage - signed URL should be generated, specified in the format - ``projects/*/locations/*``. - kms_key_name (str): - Resource name of a KMS crypto key (managed by the user) used - to encrypt/decrypt function source code objects in staging - Cloud Storage buckets. When you generate an upload url and - upload your source code, it gets copied to a staging Cloud - Storage bucket in an internal regional project. The source - code is then copied to a versioned directory in the sources - bucket in the consumer project during the function - deployment. - - It must match the pattern - ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. - - The Google Cloud Functions service account - (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - must be granted the role 'Cloud KMS CryptoKey - Encrypter/Decrypter - (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the - Key/KeyRing/Project/Organization (least access preferred). - GCF will delegate access to the Google Storage service - account in the internal project. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - kms_key_name = proto.Field( - proto.STRING, - number=2, - ) - - -class GenerateUploadUrlResponse(proto.Message): - r"""Response of ``GenerateSourceUploadUrl`` method. - - Attributes: - upload_url (str): - The generated Google Cloud Storage signed URL - that should be used for a function source code - upload. The uploaded file should be a zip - archive which contains a function. - """ - - upload_url = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateDownloadUrlRequest(proto.Message): - r"""Request of ``GenerateDownloadUrl`` method. - - Attributes: - name (str): - The name of function for which source code - Google Cloud Storage signed URL should be - generated. - version_id (int): - The optional version of function. If not set, - default, current version is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - version_id = proto.Field( - proto.UINT64, - number=2, - ) - - -class GenerateDownloadUrlResponse(proto.Message): - r"""Response of ``GenerateDownloadUrl`` method. - - Attributes: - download_url (str): - The generated Google Cloud Storage signed URL - that should be used for function source code - download. - """ - - download_url = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py b/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py deleted file mode 100644 index ab59796..0000000 --- a/owl-bot-staging/v1/google/cloud/functions_v1/types/operations.py +++ /dev/null @@ -1,108 +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 any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.functions.v1', - manifest={ - 'OperationType', - 'OperationMetadataV1', - }, -) - - -class OperationType(proto.Enum): - r"""A type of an operation.""" - OPERATION_UNSPECIFIED = 0 - CREATE_FUNCTION = 1 - UPDATE_FUNCTION = 2 - DELETE_FUNCTION = 3 - - -class OperationMetadataV1(proto.Message): - r"""Metadata describing an [Operation][google.longrunning.Operation] - - Attributes: - target (str): - Target of the operation - for example - ``projects/project-1/locations/region-1/functions/function-1`` - type_ (google.cloud.functions_v1.types.OperationType): - Type of operation. - request (google.protobuf.any_pb2.Any): - The original request that started the - operation. - version_id (int): - Version id of the function created or updated - by an API call. This field is only populated for - Create and Update operations. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update timestamp of the operation. - build_id (str): - The Cloud Build ID of the function created or - updated by an API call. This field is only - populated for Create and Update operations. - source_token (str): - An identifier for Firebase function sources. - Disclaimer: This field is only supported for - Firebase function deployments. - build_name (str): - The Cloud Build Name of the function deployment. This field - is only populated for Create and Update operations. - ``projects//locations//builds/``. - """ - - target = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - enum='OperationType', - ) - request = proto.Field( - proto.MESSAGE, - number=3, - message=any_pb2.Any, - ) - version_id = proto.Field( - proto.INT64, - number=4, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - build_id = proto.Field( - proto.STRING, - number=6, - ) - source_token = proto.Field( - proto.STRING, - number=7, - ) - build_name = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 38940e8..0000000 --- a/owl-bot-staging/v1/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', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/functions_v1/', - '--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/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py deleted file mode 100644 index f6b67dc..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] -from google.cloud import functions_v1 - - -async def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = await client.call_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py deleted file mode 100644 index 7cddbe7..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_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 CallFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] -from google.cloud import functions_v1 - - -def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = client.call_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py deleted file mode 100644 index dd6b621..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py +++ /dev/null @@ -1,53 +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 CreateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] -from google.cloud import functions_v1 - - -async def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py deleted file mode 100644 index 117d443..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py +++ /dev/null @@ -1,53 +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 CreateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] -from google.cloud import functions_v1 - - -def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # Make the request - operation = client.create_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py deleted file mode 100644 index 3051534..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] -from google.cloud import functions_v1 - - -async def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py deleted file mode 100644 index 2262e7b..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_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 DeleteFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] -from google.cloud import functions_v1 - - -def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.DeleteFunctionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py deleted file mode 100644 index 30f6889..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py +++ /dev/null @@ -1,44 +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 GenerateDownloadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] -from google.cloud import functions_v1 - - -async def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = await client.generate_download_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py deleted file mode 100644 index fbc886f..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py +++ /dev/null @@ -1,44 +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 GenerateDownloadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] -from google.cloud import functions_v1 - - -def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = client.generate_download_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py deleted file mode 100644 index 6b19431..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py +++ /dev/null @@ -1,44 +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 GenerateUploadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] -from google.cloud import functions_v1 - - -async def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = await client.generate_upload_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py deleted file mode 100644 index 6e9590a..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py +++ /dev/null @@ -1,44 +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 GenerateUploadUrl -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] -from google.cloud import functions_v1 - - -def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = client.generate_upload_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py deleted file mode 100644 index f89b7da..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] -from google.cloud import functions_v1 - - -async def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py deleted file mode 100644 index 761c41d..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_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 GetFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] -from google.cloud import functions_v1 - - -def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = client.get_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py deleted file mode 100644 index 09d1b8a..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py deleted file mode 100644 index eafe7b7..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py deleted file mode 100644 index 9a3cd36..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] -from google.cloud import functions_v1 - - -async def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py deleted file mode 100644 index 98b3760..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_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 ListFunctions -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] -from google.cloud import functions_v1 - - -def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py deleted file mode 100644 index 2d1128e..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py deleted file mode 100644 index b8b14ab..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_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 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py deleted file mode 100644 index 936744f..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py +++ /dev/null @@ -1,47 +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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py deleted file mode 100644 index c5766f3..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py +++ /dev/null @@ -1,47 +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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.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 cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py deleted file mode 100644 index 4863198..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py +++ /dev/null @@ -1,52 +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 UpdateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] -from google.cloud import functions_v1 - - -async def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py deleted file mode 100644 index 11809c3..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py +++ /dev/null @@ -1,52 +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 UpdateFunction -# 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-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] -from google.cloud import functions_v1 - - -def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # Make the request - operation = client.update_function(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json deleted file mode 100644 index 9c991cf..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_functions_v1.json +++ /dev/null @@ -1,1753 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.functions.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-functions" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.call_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CallFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CallFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", - "shortName": "call_function" - }, - "description": "Sample for CallFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.call_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CallFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CallFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CallFunctionResponse", - "shortName": "call_function" - }, - "description": "Sample for CallFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.create_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CreateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CreateFunctionRequest" - }, - { - "name": "location", - "type": "str" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_function" - }, - "description": "Sample for CreateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.create_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CreateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CreateFunctionRequest" - }, - { - "name": "location", - "type": "str" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_function" - }, - "description": "Sample for CreateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 42, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 43, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.delete_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "DeleteFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_function" - }, - "description": "Sample for DeleteFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.delete_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "DeleteFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.DeleteFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_function" - }, - "description": "Sample for DeleteFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_download_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateDownloadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", - "shortName": "generate_download_url" - }, - "description": "Sample for GenerateDownloadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_download_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateDownloadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateDownloadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateDownloadUrlResponse", - "shortName": "generate_download_url" - }, - "description": "Sample for GenerateDownloadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_upload_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateUploadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", - "shortName": "generate_upload_url" - }, - "description": "Sample for GenerateUploadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_upload_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateUploadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GenerateUploadUrlRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.GenerateUploadUrlResponse", - "shortName": "generate_upload_url" - }, - "description": "Sample for GenerateUploadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync", - "segments": [ - { - "end": 43, - "start": 27, - "type": "FULL" - }, - { - "end": 43, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 44, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GetFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CloudFunction", - "shortName": "get_function" - }, - "description": "Sample for GetFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.GetFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.types.CloudFunction", - "shortName": "get_function" - }, - "description": "Sample for GetFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_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" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.list_functions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "ListFunctions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.ListFunctionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager", - "shortName": "list_functions" - }, - "description": "Sample for ListFunctions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.list_functions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "ListFunctions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.ListFunctionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager", - "shortName": "list_functions" - }, - "description": "Sample for ListFunctions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync", - "segments": [ - { - "end": 44, - "start": 27, - "type": "FULL" - }, - { - "end": 44, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 37, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 40, - "start": 38, - "type": "REQUEST_EXECUTION" - }, - { - "end": 45, - "start": 41, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.set_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync", - "segments": [ - { - "end": 45, - "start": 27, - "type": "FULL" - }, - { - "end": 45, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 39, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 42, - "start": 40, - "type": "REQUEST_EXECUTION" - }, - { - "end": 46, - "start": 43, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 43, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 44, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync", - "segments": [ - { - "end": 46, - "start": 27, - "type": "FULL" - }, - { - "end": 46, - "start": 27, - "type": "SHORT" - }, - { - "end": 34, - "start": 32, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 40, - "start": 35, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 43, - "start": 41, - "type": "REQUEST_EXECUTION" - }, - { - "end": 47, - "start": 44, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.update_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "UpdateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_function" - }, - "description": "Sample for UpdateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.update_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "UpdateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_function" - }, - "description": "Sample for UpdateFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 33, - "start": 31, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 41, - "start": 34, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 42, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_functions_v1_keywords.py deleted file mode 100644 index 6dc057c..0000000 --- a/owl-bot-staging/v1/scripts/fixup_functions_v1_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 functionsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'call_function': ('name', 'data', ), - 'create_function': ('location', 'function', ), - 'delete_function': ('name', ), - 'generate_download_url': ('name', 'version_id', ), - 'generate_upload_url': ('parent', 'kms_key_name', ), - 'get_function': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'list_functions': ('parent', 'page_size', 'page_token', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_function': ('function', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=functionsCallTransformer(), -): - """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 functions client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index 820b19a..0000000 --- a/owl-bot-staging/v1/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-functions', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-functions", - 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] >= 2.8.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.4, < 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/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/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/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/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/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/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/v1/tests/unit/gapic/functions_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/functions_v1/__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/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py b/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py deleted file mode 100644 index 86b090e..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py +++ /dev/null @@ -1,3681 +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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock -except ImportError: - import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import 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.functions_v1.services.cloud_functions_service import CloudFunctionsServiceAsyncClient -from google.cloud.functions_v1.services.cloud_functions_service import CloudFunctionsServiceClient -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.services.cloud_functions_service import transports -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -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 CloudFunctionsServiceClient._get_default_mtls_endpoint(None) is None - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CloudFunctionsServiceClient, "grpc"), - (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CloudFunctionsServiceClient, "grpc"), - (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:443' - ) - - -def test_cloud_functions_service_client_get_transport_class(): - transport = CloudFunctionsServiceClient.get_transport_class() - available_transports = [ - transports.CloudFunctionsServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CloudFunctionsServiceClient.get_transport_class("grpc") - assert transport == transports.CloudFunctionsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) -def test_cloud_functions_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(CloudFunctionsServiceClient, '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(CloudFunctionsServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - 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, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "true"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "false"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_cloud_functions_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CloudFunctionsServiceClient, CloudFunctionsServiceAsyncClient -]) -@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) -def test_cloud_functions_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_cloud_functions_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_cloud_functions_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_cloud_functions_service_client_client_options_from_dict(): - with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CloudFunctionsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_cloud_functions_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudfunctions.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="cloudfunctions.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - functions.ListFunctionsRequest, - dict, -]) -def test_list_functions(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_functions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.ListFunctionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFunctionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_functions_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 = CloudFunctionsServiceClient( - 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_functions), - '__call__') as call: - client.list_functions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - -@pytest.mark.asyncio -async def test_list_functions_async(transport: str = 'grpc_asyncio', request_type=functions.ListFunctionsRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_functions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFunctionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_functions_async_from_dict(): - await test_list_functions_async(request_type=dict) - - -def test_list_functions_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.ListFunctionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: - call.return_value = functions.ListFunctionsResponse() - client.list_functions(request) - - # Establish that the 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_functions_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.ListFunctionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse()) - await client.list_functions(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_functions_pager(transport_name: str = "grpc"): - client = CloudFunctionsServiceClient( - 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_functions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_functions(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, functions.CloudFunction) - for i in results) -def test_list_functions_pages(transport_name: str = "grpc"): - client = CloudFunctionsServiceClient( - 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_functions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - pages = list(client.list_functions(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_functions_async_pager(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_functions(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, functions.CloudFunction) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_functions_async_pages(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_functions(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", [ - functions.GetFunctionRequest, - dict, -]) -def test_get_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CloudFunction( - name='name_value', - description='description_value', - status=functions.CloudFunctionStatus.ACTIVE, - entry_point='entry_point_value', - runtime='runtime_value', - available_memory_mb=1991, - service_account_email='service_account_email_value', - version_id=1074, - network='network_value', - max_instances=1389, - min_instances=1387, - vpc_connector='vpc_connector_value', - vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, - ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, - kms_key_name='kms_key_name_value', - build_worker_pool='build_worker_pool_value', - build_id='build_id_value', - build_name='build_name_value', - source_token='source_token_value', - docker_repository='docker_repository_value', - docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, - source_archive_url='source_archive_url_value', - https_trigger=functions.HttpsTrigger(url='url_value'), - ) - response = client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CloudFunction) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.status == functions.CloudFunctionStatus.ACTIVE - assert response.entry_point == 'entry_point_value' - assert response.runtime == 'runtime_value' - assert response.available_memory_mb == 1991 - assert response.service_account_email == 'service_account_email_value' - assert response.version_id == 1074 - assert response.network == 'network_value' - assert response.max_instances == 1389 - assert response.min_instances == 1387 - assert response.vpc_connector == 'vpc_connector_value' - assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY - assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL - assert response.kms_key_name == 'kms_key_name_value' - assert response.build_worker_pool == 'build_worker_pool_value' - assert response.build_id == 'build_id_value' - assert response.build_name == 'build_name_value' - assert response.source_token == 'source_token_value' - assert response.docker_repository == 'docker_repository_value' - assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY - - -def test_get_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.get_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - -@pytest.mark.asyncio -async def test_get_function_async(transport: str = 'grpc_asyncio', request_type=functions.GetFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction( - name='name_value', - description='description_value', - status=functions.CloudFunctionStatus.ACTIVE, - entry_point='entry_point_value', - runtime='runtime_value', - available_memory_mb=1991, - service_account_email='service_account_email_value', - version_id=1074, - network='network_value', - max_instances=1389, - min_instances=1387, - vpc_connector='vpc_connector_value', - vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, - ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, - kms_key_name='kms_key_name_value', - build_worker_pool='build_worker_pool_value', - build_id='build_id_value', - build_name='build_name_value', - source_token='source_token_value', - docker_repository='docker_repository_value', - docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, - )) - response = await client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CloudFunction) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.status == functions.CloudFunctionStatus.ACTIVE - assert response.entry_point == 'entry_point_value' - assert response.runtime == 'runtime_value' - assert response.available_memory_mb == 1991 - assert response.service_account_email == 'service_account_email_value' - assert response.version_id == 1074 - assert response.network == 'network_value' - assert response.max_instances == 1389 - assert response.min_instances == 1387 - assert response.vpc_connector == 'vpc_connector_value' - assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY - assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL - assert response.kms_key_name == 'kms_key_name_value' - assert response.build_worker_pool == 'build_worker_pool_value' - assert response.build_id == 'build_id_value' - assert response.build_name == 'build_name_value' - assert response.source_token == 'source_token_value' - assert response.docker_repository == 'docker_repository_value' - assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY - - -@pytest.mark.asyncio -async def test_get_function_async_from_dict(): - await test_get_function_async(request_type=dict) - - -def test_get_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GetFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - call.return_value = functions.CloudFunction() - client.get_function(request) - - # Establish that the 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_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GetFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) - await client.get_function(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_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CloudFunction() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_function( - 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_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.GetFunctionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CloudFunction() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_function( - 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_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.GetFunctionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.CreateFunctionRequest, - dict, -]) -def test_create_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.create_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - -@pytest.mark.asyncio -async def test_create_function_async(transport: str = 'grpc_asyncio', request_type=functions.CreateFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__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_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_function_async_from_dict(): - await test_create_function_async(request_type=dict) - - -def test_create_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CreateFunctionRequest() - - request.location = 'location_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_function(request) - - # Establish that the 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', - 'location=location_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CreateFunctionRequest() - - request.location = 'location_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_function(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', - 'location=location_value', - ) in kw['metadata'] - - -def test_create_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__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_function( - location='location_value', - function=functions.CloudFunction(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].location - mock_val = 'location_value' - assert arg == mock_val - arg = args[0].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - - -def test_create_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.CreateFunctionRequest(), - location='location_value', - function=functions.CloudFunction(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__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_function( - location='location_value', - function=functions.CloudFunction(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].location - mock_val = 'location_value' - assert arg == mock_val - arg = args[0].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.CreateFunctionRequest(), - location='location_value', - function=functions.CloudFunction(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - functions.UpdateFunctionRequest, - dict, -]) -def test_update_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.update_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - -@pytest.mark.asyncio -async def test_update_function_async(transport: str = 'grpc_asyncio', request_type=functions.UpdateFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__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_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_function_async_from_dict(): - await test_update_function_async(request_type=dict) - - -def test_update_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.UpdateFunctionRequest() - - request.function.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_function(request) - - # Establish that the 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', - 'function.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.UpdateFunctionRequest() - - request.function.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_function(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', - 'function.name=name_value', - ) in kw['metadata'] - - -def test_update_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__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_function( - function=functions.CloudFunction(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].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - - -def test_update_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.UpdateFunctionRequest(), - function=functions.CloudFunction(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__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_function( - function=functions.CloudFunction(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].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.UpdateFunctionRequest(), - function=functions.CloudFunction(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - functions.DeleteFunctionRequest, - dict, -]) -def test_delete_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_function_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 = CloudFunctionsServiceClient( - 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_function), - '__call__') as call: - client.delete_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - -@pytest.mark.asyncio -async def test_delete_function_async(transport: str = 'grpc_asyncio', request_type=functions.DeleteFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_function), - '__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_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_function_async_from_dict(): - await test_delete_function_async(request_type=dict) - - -def test_delete_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.DeleteFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_function(request) - - # Establish that the 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_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.DeleteFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_function(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_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__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_function( - 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_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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_function( - functions.DeleteFunctionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__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_function( - 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_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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_function( - functions.DeleteFunctionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.CallFunctionRequest, - dict, -]) -def test_call_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse( - execution_id='execution_id_value', - result='result_value', - error='error_value', - ) - response = client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CallFunctionResponse) - assert response.execution_id == 'execution_id_value' - assert response.result == 'result_value' - assert response.error == 'error_value' - - -def test_call_function_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 = CloudFunctionsServiceClient( - 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.call_function), - '__call__') as call: - client.call_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - -@pytest.mark.asyncio -async def test_call_function_async(transport: str = 'grpc_asyncio', request_type=functions.CallFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse( - execution_id='execution_id_value', - result='result_value', - error='error_value', - )) - response = await client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CallFunctionResponse) - assert response.execution_id == 'execution_id_value' - assert response.result == 'result_value' - assert response.error == 'error_value' - - -@pytest.mark.asyncio -async def test_call_function_async_from_dict(): - await test_call_function_async(request_type=dict) - - -def test_call_function_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CallFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - call.return_value = functions.CallFunctionResponse() - client.call_function(request) - - # Establish that the 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_call_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.CallFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) - await client.call_function(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_call_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.call_function( - name='name_value', - data='data_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 - arg = args[0].data - mock_val = 'data_value' - assert arg == mock_val - - -def test_call_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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.call_function( - functions.CallFunctionRequest(), - name='name_value', - data='data_value', - ) - -@pytest.mark.asyncio -async def test_call_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.call_function( - name='name_value', - data='data_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 - arg = args[0].data - mock_val = 'data_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_call_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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.call_function( - functions.CallFunctionRequest(), - name='name_value', - data='data_value', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateUploadUrlRequest, - dict, -]) -def test_generate_upload_url(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.GenerateUploadUrlResponse( - upload_url='upload_url_value', - ) - response = client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateUploadUrlResponse) - assert response.upload_url == 'upload_url_value' - - -def test_generate_upload_url_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 = CloudFunctionsServiceClient( - 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.generate_upload_url), - '__call__') as call: - client.generate_upload_url() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - -@pytest.mark.asyncio -async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateUploadUrlRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse( - upload_url='upload_url_value', - )) - response = await client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateUploadUrlResponse) - assert response.upload_url == 'upload_url_value' - - -@pytest.mark.asyncio -async def test_generate_upload_url_async_from_dict(): - await test_generate_upload_url_async(request_type=dict) - - -def test_generate_upload_url_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateUploadUrlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - call.return_value = functions.GenerateUploadUrlResponse() - client.generate_upload_url(request) - - # Establish that the 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_generate_upload_url_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateUploadUrlRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse()) - await client.generate_upload_url(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'] - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateDownloadUrlRequest, - dict, -]) -def test_generate_download_url(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.GenerateDownloadUrlResponse( - download_url='download_url_value', - ) - response = client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateDownloadUrlResponse) - assert response.download_url == 'download_url_value' - - -def test_generate_download_url_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 = CloudFunctionsServiceClient( - 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.generate_download_url), - '__call__') as call: - client.generate_download_url() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - -@pytest.mark.asyncio -async def test_generate_download_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateDownloadUrlRequest): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse( - download_url='download_url_value', - )) - response = await client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.GenerateDownloadUrlResponse) - assert response.download_url == 'download_url_value' - - -@pytest.mark.asyncio -async def test_generate_download_url_async_from_dict(): - await test_generate_download_url_async(request_type=dict) - - -def test_generate_download_url_field_headers(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateDownloadUrlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - call.return_value = functions.GenerateDownloadUrlResponse() - client.generate_download_url(request) - - # Establish that the 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_generate_download_url_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = functions.GenerateDownloadUrlRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse()) - await client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceClient( - 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.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceClient( - 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.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CloudFunctionsServiceClient( - 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.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CloudFunctionsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, -]) -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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CloudFunctionsServiceGrpcTransport, - ) - -def test_cloud_functions_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CloudFunctionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_cloud_functions_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CloudFunctionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_functions', - 'get_function', - 'create_function', - 'update_function', - 'delete_function', - 'call_function', - 'generate_upload_url', - 'generate_download_url', - 'set_iam_policy', - 'get_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_cloud_functions_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudFunctionsServiceTransport( - 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_cloud_functions_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudFunctionsServiceTransport() - adc.assert_called_once() - - -def test_cloud_functions_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CloudFunctionsServiceClient() - 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.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, - ], -) -def test_cloud_functions_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, - ], -) -def test_cloud_functions_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CloudFunctionsServiceGrpcTransport, grpc_helpers), - (transports.CloudFunctionsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_cloud_functions_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "cloudfunctions.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="cloudfunctions.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_cloud_functions_service_host_no_port(transport_name): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_cloud_functions_service_host_with_port(transport_name): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:8000' - ) - -def test_cloud_functions_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CloudFunctionsServiceGrpcTransport( - 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_cloud_functions_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( - 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.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_cloud_functions_service_grpc_lro_client(): - client = CloudFunctionsServiceClient( - 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_cloud_functions_service_grpc_lro_async_client(): - client = CloudFunctionsServiceAsyncClient( - 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_cloud_function_path(): - project = "squid" - location = "clam" - function = "whelk" - expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) - actual = CloudFunctionsServiceClient.cloud_function_path(project, location, function) - assert expected == actual - - -def test_parse_cloud_function_path(): - expected = { - "project": "octopus", - "location": "oyster", - "function": "nudibranch", - } - path = CloudFunctionsServiceClient.cloud_function_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_cloud_function_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 = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_crypto_key_path(path) - assert expected == actual - -def test_repository_path(): - project = "whelk" - location = "octopus" - repository = "oyster" - expected = "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) - actual = CloudFunctionsServiceClient.repository_path(project, location, repository) - assert expected == actual - - -def test_parse_repository_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "repository": "mussel", - } - path = CloudFunctionsServiceClient.repository_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_repository_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CloudFunctionsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = CloudFunctionsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = CloudFunctionsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = CloudFunctionsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CloudFunctionsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = CloudFunctionsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = CloudFunctionsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = CloudFunctionsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CloudFunctionsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = CloudFunctionsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.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.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CloudFunctionsServiceClient.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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceClient( - 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", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport), -]) -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, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc deleted file mode 100644 index ca93bdf..0000000 --- a/owl-bot-staging/v2/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/functions/__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 3e19820..0000000 --- a/owl-bot-staging/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/functions *.py -recursive-include google/cloud/functions_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst deleted file mode 100644 index 533650a..0000000 --- a/owl-bot-staging/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Functions 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 Functions 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 3464a12..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-functions 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-functions" -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-functions-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-functions.tex", - u"google-cloud-functions 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-functions", - u"Google Cloud Functions 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-functions", - u"google-cloud-functions Documentation", - author, - "google-cloud-functions", - "GAPIC library for Google Cloud Functions 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 15756cf..0000000 --- a/owl-bot-staging/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - functions_v2/services - functions_v2/types diff --git a/owl-bot-staging/v2/google/cloud/functions/__init__.py b/owl-bot-staging/v2/google/cloud/functions/__init__.py deleted file mode 100644 index 34f37ea..0000000 --- a/owl-bot-staging/v2/google/cloud/functions/__init__.py +++ /dev/null @@ -1,77 +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.functions_v2.services.function_service.client import FunctionServiceClient -from google.cloud.functions_v2.services.function_service.async_client import FunctionServiceAsyncClient - -from google.cloud.functions_v2.types.functions import BuildConfig -from google.cloud.functions_v2.types.functions import CreateFunctionRequest -from google.cloud.functions_v2.types.functions import DeleteFunctionRequest -from google.cloud.functions_v2.types.functions import EventFilter -from google.cloud.functions_v2.types.functions import EventTrigger -from google.cloud.functions_v2.types.functions import Function -from google.cloud.functions_v2.types.functions import GenerateDownloadUrlRequest -from google.cloud.functions_v2.types.functions import GenerateDownloadUrlResponse -from google.cloud.functions_v2.types.functions import GenerateUploadUrlRequest -from google.cloud.functions_v2.types.functions import GenerateUploadUrlResponse -from google.cloud.functions_v2.types.functions import GetFunctionRequest -from google.cloud.functions_v2.types.functions import ListFunctionsRequest -from google.cloud.functions_v2.types.functions import ListFunctionsResponse -from google.cloud.functions_v2.types.functions import ListRuntimesRequest -from google.cloud.functions_v2.types.functions import ListRuntimesResponse -from google.cloud.functions_v2.types.functions import OperationMetadata -from google.cloud.functions_v2.types.functions import RepoSource -from google.cloud.functions_v2.types.functions import SecretEnvVar -from google.cloud.functions_v2.types.functions import SecretVolume -from google.cloud.functions_v2.types.functions import ServiceConfig -from google.cloud.functions_v2.types.functions import Source -from google.cloud.functions_v2.types.functions import SourceProvenance -from google.cloud.functions_v2.types.functions import Stage -from google.cloud.functions_v2.types.functions import StateMessage -from google.cloud.functions_v2.types.functions import StorageSource -from google.cloud.functions_v2.types.functions import UpdateFunctionRequest -from google.cloud.functions_v2.types.functions import Environment - -__all__ = ('FunctionServiceClient', - 'FunctionServiceAsyncClient', - 'BuildConfig', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventFilter', - 'EventTrigger', - 'Function', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'ListRuntimesRequest', - 'ListRuntimesResponse', - 'OperationMetadata', - 'RepoSource', - 'SecretEnvVar', - 'SecretVolume', - 'ServiceConfig', - 'Source', - 'SourceProvenance', - 'Stage', - 'StateMessage', - 'StorageSource', - 'UpdateFunctionRequest', - 'Environment', -) diff --git a/owl-bot-staging/v2/google/cloud/functions/py.typed b/owl-bot-staging/v2/google/cloud/functions/py.typed deleted file mode 100644 index 982ebb1..0000000 --- a/owl-bot-staging/v2/google/cloud/functions/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/__init__.py b/owl-bot-staging/v2/google/cloud/functions_v2/__init__.py deleted file mode 100644 index e858335..0000000 --- a/owl-bot-staging/v2/google/cloud/functions_v2/__init__.py +++ /dev/null @@ -1,78 +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.function_service import FunctionServiceClient -from .services.function_service import FunctionServiceAsyncClient - -from .types.functions import BuildConfig -from .types.functions import CreateFunctionRequest -from .types.functions import DeleteFunctionRequest -from .types.functions import EventFilter -from .types.functions import EventTrigger -from .types.functions import Function -from .types.functions import GenerateDownloadUrlRequest -from .types.functions import GenerateDownloadUrlResponse -from .types.functions import GenerateUploadUrlRequest -from .types.functions import GenerateUploadUrlResponse -from .types.functions import GetFunctionRequest -from .types.functions import ListFunctionsRequest -from .types.functions import ListFunctionsResponse -from .types.functions import ListRuntimesRequest -from .types.functions import ListRuntimesResponse -from .types.functions import OperationMetadata -from .types.functions import RepoSource -from .types.functions import SecretEnvVar -from .types.functions import SecretVolume -from .types.functions import ServiceConfig -from .types.functions import Source -from .types.functions import SourceProvenance -from .types.functions import Stage -from .types.functions import StateMessage -from .types.functions import StorageSource -from .types.functions import UpdateFunctionRequest -from .types.functions import Environment - -__all__ = ( - 'FunctionServiceAsyncClient', -'BuildConfig', -'CreateFunctionRequest', -'DeleteFunctionRequest', -'Environment', -'EventFilter', -'EventTrigger', -'Function', -'FunctionServiceClient', -'GenerateDownloadUrlRequest', -'GenerateDownloadUrlResponse', -'GenerateUploadUrlRequest', -'GenerateUploadUrlResponse', -'GetFunctionRequest', -'ListFunctionsRequest', -'ListFunctionsResponse', -'ListRuntimesRequest', -'ListRuntimesResponse', -'OperationMetadata', -'RepoSource', -'SecretEnvVar', -'SecretVolume', -'ServiceConfig', -'Source', -'SourceProvenance', -'Stage', -'StateMessage', -'StorageSource', -'UpdateFunctionRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/py.typed b/owl-bot-staging/v2/google/cloud/functions_v2/py.typed deleted file mode 100644 index 982ebb1..0000000 --- a/owl-bot-staging/v2/google/cloud/functions_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. 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 5dcdf9d..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', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/functions_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/setup.py b/owl-bot-staging/v2/setup.py deleted file mode 100644 index 820b19a..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-functions', - author="Google LLC", - author_email="googleapis-packages@google.com", - url="https://github.com/googleapis/python-google-cloud-functions", - 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] >= 2.8.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.4, < 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/functions_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/functions_v2/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v2/tests/unit/gapic/functions_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/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py diff --git a/owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py b/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py rename to samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_functions_v2.json b/samples/generated_samples/snippet_metadata_functions_v2.json similarity index 100% rename from owl-bot-staging/v2/samples/generated_samples/snippet_metadata_functions_v2.json rename to samples/generated_samples/snippet_metadata_functions_v2.json diff --git a/owl-bot-staging/v2/scripts/fixup_functions_v2_keywords.py b/scripts/fixup_functions_v2_keywords.py similarity index 100% rename from owl-bot-staging/v2/scripts/fixup_functions_v2_keywords.py rename to scripts/fixup_functions_v2_keywords.py diff --git a/owl-bot-staging/v2/google/cloud/functions_v2/services/__init__.py b/tests/unit/gapic/functions_v2/__init__.py similarity index 100% rename from owl-bot-staging/v2/google/cloud/functions_v2/services/__init__.py rename to tests/unit/gapic/functions_v2/__init__.py diff --git a/owl-bot-staging/v2/tests/unit/gapic/functions_v2/test_function_service.py b/tests/unit/gapic/functions_v2/test_function_service.py similarity index 77% rename from owl-bot-staging/v2/tests/unit/gapic/functions_v2/test_function_service.py rename to tests/unit/gapic/functions_v2/test_function_service.py index 724b533..a28e59d 100644 --- a/owl-bot-staging/v2/tests/unit/gapic/functions_v2/test_function_service.py +++ b/tests/unit/gapic/functions_v2/test_function_service.py @@ -14,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,30 +22,23 @@ except ImportError: import mock -import grpc -from grpc.experimental import aio import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) 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 +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.cloud.functions_v2.services.function_service import FunctionServiceAsyncClient -from google.cloud.functions_v2.services.function_service import FunctionServiceClient -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.services.function_service import transports -from google.cloud.functions_v2.types import functions from google.cloud.location import locations_pb2 from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import options_pb2 # type: ignore @@ -53,7 +47,18 @@ from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -import google.auth +import grpc +from grpc.experimental import aio +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest + +from google.cloud.functions_v2.services.function_service import ( + FunctionServiceAsyncClient, + FunctionServiceClient, + pagers, + transports, +) +from google.cloud.functions_v2.types import functions def client_cert_source_callback(): @@ -64,7 +69,11 @@ def client_cert_source_callback(): # 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 + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) def test__get_default_mtls_endpoint(): @@ -75,66 +84,103 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert FunctionServiceClient._get_default_mtls_endpoint(None) is None - assert FunctionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert FunctionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert FunctionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert FunctionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert FunctionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (FunctionServiceClient, "grpc"), - (FunctionServiceAsyncClient, "grpc_asyncio"), -]) -def test_function_service_client_from_service_account_info(client_class, transport_name): + assert ( + FunctionServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + FunctionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + FunctionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FunctionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FunctionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (FunctionServiceClient, "grpc"), + (FunctionServiceAsyncClient, "grpc_asyncio"), + ], +) +def test_function_service_client_from_service_account_info( + client_class, transport_name +): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + 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 == ( - 'cloudfunctions.googleapis.com:443' - ) + assert client.transport._host == ("cloudfunctions.googleapis.com:443") -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.FunctionServiceGrpcTransport, "grpc"), - (transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_function_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.FunctionServiceGrpcTransport, "grpc"), + (transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_function_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + 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", [ - (FunctionServiceClient, "grpc"), - (FunctionServiceAsyncClient, "grpc_asyncio"), -]) -def test_function_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (FunctionServiceClient, "grpc"), + (FunctionServiceAsyncClient, "grpc_asyncio"), + ], +) +def test_function_service_client_from_service_account_file( + client_class, transport_name +): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + 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) + 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) + 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 == ( - 'cloudfunctions.googleapis.com:443' - ) + assert client.transport._host == ("cloudfunctions.googleapis.com:443") def test_function_service_client_get_transport_class(): @@ -148,29 +194,44 @@ def test_function_service_client_get_transport_class(): assert transport == transports.FunctionServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc"), - (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(FunctionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceClient)) -@mock.patch.object(FunctionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceAsyncClient)) -def test_function_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc"), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + FunctionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceClient), +) +@mock.patch.object( + FunctionServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceAsyncClient), +) +def test_function_service_client_client_options( + client_class, transport_class, transport_name +): # Check that if channel is provided we won't create a new one. - with mock.patch.object(FunctionServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(FunctionServiceClient, "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(FunctionServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(FunctionServiceClient, "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: + 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( @@ -188,7 +249,7 @@ def test_function_service_client_client_options(client_class, transport_class, t # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -206,7 +267,7 @@ def test_function_service_client_client_options(client_class, transport_class, t # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -228,13 +289,15 @@ def test_function_service_client_client_options(client_class, transport_class, t 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 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: + 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( @@ -249,8 +312,10 @@ def test_function_service_client_client_options(client_class, transport_class, t api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( @@ -262,27 +327,65 @@ def test_function_service_client_client_options(client_class, transport_class, t quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com" + api_audience="https://language.googleapis.com", ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc", "true"), - (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc", "false"), - (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(FunctionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceClient)) -@mock.patch.object(FunctionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceAsyncClient)) + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + FunctionServiceClient, + transports.FunctionServiceGrpcTransport, + "grpc", + "true", + ), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + FunctionServiceClient, + transports.FunctionServiceGrpcTransport, + "grpc", + "false", + ), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + FunctionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceClient), +) +@mock.patch.object( + FunctionServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_function_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_function_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: + 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) @@ -307,10 +410,18 @@ def test_function_service_client_mtls_env_auto(client_class, transport_class, tr # 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): + 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 @@ -333,9 +444,14 @@ def test_function_service_client_mtls_env_auto(client_class, transport_class, tr ) # 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): + 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( @@ -351,19 +467,31 @@ def test_function_service_client_mtls_env_auto(client_class, transport_class, tr ) -@pytest.mark.parametrize("client_class", [ - FunctionServiceClient, FunctionServiceAsyncClient -]) -@mock.patch.object(FunctionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceClient)) -@mock.patch.object(FunctionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FunctionServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [FunctionServiceClient, FunctionServiceAsyncClient] +) +@mock.patch.object( + FunctionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceClient), +) +@mock.patch.object( + FunctionServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceAsyncClient), +) def test_function_service_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + 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 @@ -371,8 +499,12 @@ def test_function_service_client_get_mtls_endpoint_and_cert_source(client_class) 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) + 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 @@ -390,30 +522,51 @@ def test_function_service_client_get_mtls_endpoint_and_cert_source(client_class) # 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): + 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() + 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", [ - (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc"), - (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_function_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc"), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_function_service_client_client_options_scopes( + client_class, transport_class, transport_name +): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -428,17 +581,31 @@ def test_function_service_client_client_options_scopes(client_class, transport_c api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc", grpc_helpers), - (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_function_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + FunctionServiceClient, + transports.FunctionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_function_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -453,11 +620,14 @@ def test_function_service_client_client_options_credentials_file(client_class, t api_audience=None, ) + def test_function_service_client_client_options_from_dict(): - with mock.patch('google.cloud.functions_v2.services.function_service.transports.FunctionServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.cloud.functions_v2.services.function_service.transports.FunctionServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = FunctionServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -472,17 +642,30 @@ def test_function_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc", grpc_helpers), - (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_function_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + FunctionServiceClient, + transports.FunctionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_function_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -515,9 +698,7 @@ def test_function_service_client_create_channel_credentials_file(client_class, t credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=None, default_host="cloudfunctions.googleapis.com", ssl_credentials=None, @@ -528,11 +709,14 @@ def test_function_service_client_create_channel_credentials_file(client_class, t ) -@pytest.mark.parametrize("request_type", [ - functions.GetFunctionRequest, - dict, -]) -def test_get_function(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + functions.GetFunctionRequest, + dict, + ], +) +def test_get_function(request_type, transport: str = "grpc"): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -543,14 +727,12 @@ def test_get_function(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: + with mock.patch.object(type(client.transport.get_function), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = functions.Function( - name='name_value', + name="name_value", environment=functions.Environment.GEN_1, - description='description_value', + description="description_value", state=functions.Function.State.ACTIVE, ) response = client.get_function(request) @@ -562,9 +744,9 @@ def test_get_function(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, functions.Function) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.environment == functions.Environment.GEN_1 - assert response.description == 'description_value' + assert response.description == "description_value" assert response.state == functions.Function.State.ACTIVE @@ -573,20 +755,21 @@ def test_get_function_empty_call(): # i.e. request == None and no flattened fields passed, work. client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: + with mock.patch.object(type(client.transport.get_function), "__call__") as call: client.get_function() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == functions.GetFunctionRequest() + @pytest.mark.asyncio -async def test_get_function_async(transport: str = 'grpc_asyncio', request_type=functions.GetFunctionRequest): +async def test_get_function_async( + transport: str = "grpc_asyncio", request_type=functions.GetFunctionRequest +): client = FunctionServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -597,16 +780,16 @@ async def test_get_function_async(transport: str = 'grpc_asyncio', request_type= request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: + with mock.patch.object(type(client.transport.get_function), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.Function( - name='name_value', - environment=functions.Environment.GEN_1, - description='description_value', - state=functions.Function.State.ACTIVE, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.Function( + name="name_value", + environment=functions.Environment.GEN_1, + description="description_value", + state=functions.Function.State.ACTIVE, + ) + ) response = await client.get_function(request) # Establish that the underlying gRPC stub method was called. @@ -616,9 +799,9 @@ async def test_get_function_async(transport: str = 'grpc_asyncio', request_type= # Establish that the response is the type that we expect. assert isinstance(response, functions.Function) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.environment == functions.Environment.GEN_1 - assert response.description == 'description_value' + assert response.description == "description_value" assert response.state == functions.Function.State.ACTIVE @@ -636,12 +819,10 @@ def test_get_function_field_headers(): # a field header. Set these to a non-empty value. request = functions.GetFunctionRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: + with mock.patch.object(type(client.transport.get_function), "__call__") as call: call.return_value = functions.Function() client.get_function(request) @@ -653,9 +834,9 @@ def test_get_function_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -668,12 +849,10 @@ async def test_get_function_field_headers_async(): # a field header. Set these to a non-empty value. request = functions.GetFunctionRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: + with mock.patch.object(type(client.transport.get_function), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.Function()) await client.get_function(request) @@ -685,9 +864,9 @@ async def test_get_function_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_function_flattened(): @@ -696,15 +875,13 @@ def test_get_function_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: + with mock.patch.object(type(client.transport.get_function), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = functions.Function() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_function( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -712,7 +889,7 @@ def test_get_function_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -726,9 +903,10 @@ def test_get_function_flattened_error(): with pytest.raises(ValueError): client.get_function( functions.GetFunctionRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_function_flattened_async(): client = FunctionServiceAsyncClient( @@ -736,9 +914,7 @@ async def test_get_function_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_function), - '__call__') as call: + with mock.patch.object(type(client.transport.get_function), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = functions.Function() @@ -746,7 +922,7 @@ async def test_get_function_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_function( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -754,9 +930,10 @@ async def test_get_function_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_function_flattened_error_async(): client = FunctionServiceAsyncClient( @@ -768,15 +945,18 @@ async def test_get_function_flattened_error_async(): with pytest.raises(ValueError): await client.get_function( functions.GetFunctionRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - functions.ListFunctionsRequest, - dict, -]) -def test_list_functions(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + functions.ListFunctionsRequest, + dict, + ], +) +def test_list_functions(request_type, transport: str = "grpc"): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -787,13 +967,11 @@ def test_list_functions(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = functions.ListFunctionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) response = client.list_functions(request) @@ -804,8 +982,8 @@ def test_list_functions(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListFunctionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] def test_list_functions_empty_call(): @@ -813,20 +991,21 @@ def test_list_functions_empty_call(): # i.e. request == None and no flattened fields passed, work. client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: client.list_functions() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == functions.ListFunctionsRequest() + @pytest.mark.asyncio -async def test_list_functions_async(transport: str = 'grpc_asyncio', request_type=functions.ListFunctionsRequest): +async def test_list_functions_async( + transport: str = "grpc_asyncio", request_type=functions.ListFunctionsRequest +): client = FunctionServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -837,14 +1016,14 @@ async def test_list_functions_async(transport: str = 'grpc_asyncio', request_typ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListFunctionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) response = await client.list_functions(request) # Establish that the underlying gRPC stub method was called. @@ -854,8 +1033,8 @@ async def test_list_functions_async(transport: str = 'grpc_asyncio', request_typ # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListFunctionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio @@ -872,12 +1051,10 @@ def test_list_functions_field_headers(): # a field header. Set these to a non-empty value. request = functions.ListFunctionsRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: call.return_value = functions.ListFunctionsResponse() client.list_functions(request) @@ -889,9 +1066,9 @@ def test_list_functions_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -904,13 +1081,13 @@ async def test_list_functions_field_headers_async(): # a field header. Set these to a non-empty value. request = functions.ListFunctionsRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse()) + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListFunctionsResponse() + ) await client.list_functions(request) # Establish that the underlying gRPC stub method was called. @@ -921,9 +1098,9 @@ async def test_list_functions_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_list_functions_flattened(): @@ -932,15 +1109,13 @@ def test_list_functions_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = functions.ListFunctionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_functions( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -948,7 +1123,7 @@ def test_list_functions_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val @@ -962,9 +1137,10 @@ def test_list_functions_flattened_error(): with pytest.raises(ValueError): client.list_functions( functions.ListFunctionsRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_functions_flattened_async(): client = FunctionServiceAsyncClient( @@ -972,17 +1148,17 @@ async def test_list_functions_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = functions.ListFunctionsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListFunctionsResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListFunctionsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_functions( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -990,9 +1166,10 @@ async def test_list_functions_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val + @pytest.mark.asyncio async def test_list_functions_flattened_error_async(): client = FunctionServiceAsyncClient( @@ -1004,7 +1181,7 @@ async def test_list_functions_flattened_error_async(): with pytest.raises(ValueError): await client.list_functions( functions.ListFunctionsRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1015,9 +1192,7 @@ def test_list_functions_pager(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( functions.ListFunctionsResponse( @@ -1026,17 +1201,17 @@ def test_list_functions_pager(transport_name: str = "grpc"): functions.Function(), functions.Function(), ], - next_page_token='abc', + next_page_token="abc", ), functions.ListFunctionsResponse( functions=[], - next_page_token='def', + next_page_token="def", ), functions.ListFunctionsResponse( functions=[ functions.Function(), ], - next_page_token='ghi', + next_page_token="ghi", ), functions.ListFunctionsResponse( functions=[ @@ -1049,9 +1224,7 @@ def test_list_functions_pager(transport_name: str = "grpc"): metadata = () metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) pager = client.list_functions(request={}) @@ -1059,8 +1232,9 @@ def test_list_functions_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, functions.Function) - for i in results) + assert all(isinstance(i, functions.Function) for i in results) + + def test_list_functions_pages(transport_name: str = "grpc"): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials, @@ -1068,9 +1242,7 @@ def test_list_functions_pages(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_functions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( functions.ListFunctionsResponse( @@ -1079,17 +1251,17 @@ def test_list_functions_pages(transport_name: str = "grpc"): functions.Function(), functions.Function(), ], - next_page_token='abc', + next_page_token="abc", ), functions.ListFunctionsResponse( functions=[], - next_page_token='def', + next_page_token="def", ), functions.ListFunctionsResponse( functions=[ functions.Function(), ], - next_page_token='ghi', + next_page_token="ghi", ), functions.ListFunctionsResponse( functions=[ @@ -1100,9 +1272,10 @@ def test_list_functions_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_functions(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token + @pytest.mark.asyncio async def test_list_functions_async_pager(): client = FunctionServiceAsyncClient( @@ -1111,8 +1284,8 @@ async def test_list_functions_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_functions), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_functions), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( functions.ListFunctionsResponse( @@ -1121,17 +1294,17 @@ async def test_list_functions_async_pager(): functions.Function(), functions.Function(), ], - next_page_token='abc', + next_page_token="abc", ), functions.ListFunctionsResponse( functions=[], - next_page_token='def', + next_page_token="def", ), functions.ListFunctionsResponse( functions=[ functions.Function(), ], - next_page_token='ghi', + next_page_token="ghi", ), functions.ListFunctionsResponse( functions=[ @@ -1141,15 +1314,16 @@ async def test_list_functions_async_pager(): ), RuntimeError, ) - async_pager = await client.list_functions(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_functions( + request={}, + ) + assert async_pager.next_page_token == "abc" responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, functions.Function) - for i in responses) + assert all(isinstance(i, functions.Function) for i in responses) @pytest.mark.asyncio @@ -1160,8 +1334,8 @@ async def test_list_functions_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_functions), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_functions), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( functions.ListFunctionsResponse( @@ -1170,17 +1344,17 @@ async def test_list_functions_async_pages(): functions.Function(), functions.Function(), ], - next_page_token='abc', + next_page_token="abc", ), functions.ListFunctionsResponse( functions=[], - next_page_token='def', + next_page_token="def", ), functions.ListFunctionsResponse( functions=[ functions.Function(), ], - next_page_token='ghi', + next_page_token="ghi", ), functions.ListFunctionsResponse( functions=[ @@ -1191,16 +1365,22 @@ async def test_list_functions_async_pages(): RuntimeError, ) pages = [] - async for page_ in (await client.list_functions(request={})).pages: # pragma: no branch + async for page_ in ( + await client.list_functions(request={}) + ).pages: # pragma: no branch pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize("request_type", [ - functions.CreateFunctionRequest, - dict, -]) -def test_create_function(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + functions.CreateFunctionRequest, + dict, + ], +) +def test_create_function(request_type, transport: str = "grpc"): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1211,11 +1391,9 @@ def test_create_function(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: + with mock.patch.object(type(client.transport.create_function), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.create_function(request) # Establish that the underlying gRPC stub method was called. @@ -1232,20 +1410,21 @@ def test_create_function_empty_call(): # i.e. request == None and no flattened fields passed, work. client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: + with mock.patch.object(type(client.transport.create_function), "__call__") as call: client.create_function() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == functions.CreateFunctionRequest() + @pytest.mark.asyncio -async def test_create_function_async(transport: str = 'grpc_asyncio', request_type=functions.CreateFunctionRequest): +async def test_create_function_async( + transport: str = "grpc_asyncio", request_type=functions.CreateFunctionRequest +): client = FunctionServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1256,12 +1435,10 @@ async def test_create_function_async(transport: str = 'grpc_asyncio', request_ty request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: + with mock.patch.object(type(client.transport.create_function), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.create_function(request) @@ -1288,13 +1465,11 @@ def test_create_function_field_headers(): # a field header. Set these to a non-empty value. request = functions.CreateFunctionRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + with mock.patch.object(type(client.transport.create_function), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.create_function(request) # Establish that the underlying gRPC stub method was called. @@ -1305,9 +1480,9 @@ def test_create_function_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1320,13 +1495,13 @@ async def test_create_function_field_headers_async(): # a field header. Set these to a non-empty value. request = functions.CreateFunctionRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + with mock.patch.object(type(client.transport.create_function), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.create_function(request) # Establish that the underlying gRPC stub method was called. @@ -1337,9 +1512,9 @@ async def test_create_function_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_create_function_flattened(): @@ -1348,17 +1523,15 @@ def test_create_function_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: + with mock.patch.object(type(client.transport.create_function), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + 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_function( - parent='parent_value', - function=functions.Function(name='name_value'), - function_id='function_id_value', + parent="parent_value", + function=functions.Function(name="name_value"), + function_id="function_id_value", ) # Establish that the underlying call was made with the expected @@ -1366,13 +1539,13 @@ def test_create_function_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].function - mock_val = functions.Function(name='name_value') + mock_val = functions.Function(name="name_value") assert arg == mock_val arg = args[0].function_id - mock_val = 'function_id_value' + mock_val = "function_id_value" assert arg == mock_val @@ -1386,11 +1559,12 @@ def test_create_function_flattened_error(): with pytest.raises(ValueError): client.create_function( functions.CreateFunctionRequest(), - parent='parent_value', - function=functions.Function(name='name_value'), - function_id='function_id_value', + parent="parent_value", + function=functions.Function(name="name_value"), + function_id="function_id_value", ) + @pytest.mark.asyncio async def test_create_function_flattened_async(): client = FunctionServiceAsyncClient( @@ -1398,21 +1572,19 @@ async def test_create_function_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_function), - '__call__') as call: + with mock.patch.object(type(client.transport.create_function), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + 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_function( - parent='parent_value', - function=functions.Function(name='name_value'), - function_id='function_id_value', + parent="parent_value", + function=functions.Function(name="name_value"), + function_id="function_id_value", ) # Establish that the underlying call was made with the expected @@ -1420,15 +1592,16 @@ async def test_create_function_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].function - mock_val = functions.Function(name='name_value') + mock_val = functions.Function(name="name_value") assert arg == mock_val arg = args[0].function_id - mock_val = 'function_id_value' + mock_val = "function_id_value" assert arg == mock_val + @pytest.mark.asyncio async def test_create_function_flattened_error_async(): client = FunctionServiceAsyncClient( @@ -1440,17 +1613,20 @@ async def test_create_function_flattened_error_async(): with pytest.raises(ValueError): await client.create_function( functions.CreateFunctionRequest(), - parent='parent_value', - function=functions.Function(name='name_value'), - function_id='function_id_value', + parent="parent_value", + function=functions.Function(name="name_value"), + function_id="function_id_value", ) -@pytest.mark.parametrize("request_type", [ - functions.UpdateFunctionRequest, - dict, -]) -def test_update_function(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + functions.UpdateFunctionRequest, + dict, + ], +) +def test_update_function(request_type, transport: str = "grpc"): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1461,11 +1637,9 @@ def test_update_function(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: + with mock.patch.object(type(client.transport.update_function), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.update_function(request) # Establish that the underlying gRPC stub method was called. @@ -1482,20 +1656,21 @@ def test_update_function_empty_call(): # i.e. request == None and no flattened fields passed, work. client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: + with mock.patch.object(type(client.transport.update_function), "__call__") as call: client.update_function() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == functions.UpdateFunctionRequest() + @pytest.mark.asyncio -async def test_update_function_async(transport: str = 'grpc_asyncio', request_type=functions.UpdateFunctionRequest): +async def test_update_function_async( + transport: str = "grpc_asyncio", request_type=functions.UpdateFunctionRequest +): client = FunctionServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1506,12 +1681,10 @@ async def test_update_function_async(transport: str = 'grpc_asyncio', request_ty request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: + with mock.patch.object(type(client.transport.update_function), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.update_function(request) @@ -1538,13 +1711,11 @@ def test_update_function_field_headers(): # a field header. Set these to a non-empty value. request = functions.UpdateFunctionRequest() - request.function.name = 'name_value' + request.function.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + with mock.patch.object(type(client.transport.update_function), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.update_function(request) # Establish that the underlying gRPC stub method was called. @@ -1555,9 +1726,9 @@ def test_update_function_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'function.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "function.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1570,13 +1741,13 @@ async def test_update_function_field_headers_async(): # a field header. Set these to a non-empty value. request = functions.UpdateFunctionRequest() - request.function.name = 'name_value' + request.function.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + with mock.patch.object(type(client.transport.update_function), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.update_function(request) # Establish that the underlying gRPC stub method was called. @@ -1587,9 +1758,9 @@ async def test_update_function_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'function.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "function.name=name_value", + ) in kw["metadata"] def test_update_function_flattened(): @@ -1598,16 +1769,14 @@ def test_update_function_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: + with mock.patch.object(type(client.transport.update_function), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + 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_function( - function=functions.Function(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + function=functions.Function(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1615,10 +1784,10 @@ def test_update_function_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].function - mock_val = functions.Function(name='name_value') + mock_val = functions.Function(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1632,10 +1801,11 @@ def test_update_function_flattened_error(): with pytest.raises(ValueError): client.update_function( functions.UpdateFunctionRequest(), - function=functions.Function(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + function=functions.Function(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_function_flattened_async(): client = FunctionServiceAsyncClient( @@ -1643,20 +1813,18 @@ async def test_update_function_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_function), - '__call__') as call: + with mock.patch.object(type(client.transport.update_function), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + 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_function( - function=functions.Function(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + function=functions.Function(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1664,12 +1832,13 @@ async def test_update_function_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].function - mock_val = functions.Function(name='name_value') + mock_val = functions.Function(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_function_flattened_error_async(): client = FunctionServiceAsyncClient( @@ -1681,16 +1850,19 @@ async def test_update_function_flattened_error_async(): with pytest.raises(ValueError): await client.update_function( functions.UpdateFunctionRequest(), - function=functions.Function(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + function=functions.Function(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - functions.DeleteFunctionRequest, - dict, -]) -def test_delete_function(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + functions.DeleteFunctionRequest, + dict, + ], +) +def test_delete_function(request_type, transport: str = "grpc"): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1701,11 +1873,9 @@ def test_delete_function(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.delete_function(request) # Establish that the underlying gRPC stub method was called. @@ -1722,20 +1892,21 @@ def test_delete_function_empty_call(): # i.e. request == None and no flattened fields passed, work. client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: client.delete_function() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == functions.DeleteFunctionRequest() + @pytest.mark.asyncio -async def test_delete_function_async(transport: str = 'grpc_asyncio', request_type=functions.DeleteFunctionRequest): +async def test_delete_function_async( + transport: str = "grpc_asyncio", request_type=functions.DeleteFunctionRequest +): client = FunctionServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1746,12 +1917,10 @@ async def test_delete_function_async(transport: str = 'grpc_asyncio', request_ty request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.delete_function(request) @@ -1778,13 +1947,11 @@ def test_delete_function_field_headers(): # a field header. Set these to a non-empty value. request = functions.DeleteFunctionRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.delete_function(request) # Establish that the underlying gRPC stub method was called. @@ -1795,9 +1962,9 @@ def test_delete_function_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1810,13 +1977,13 @@ async def test_delete_function_field_headers_async(): # a field header. Set these to a non-empty value. request = functions.DeleteFunctionRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.delete_function(request) # Establish that the underlying gRPC stub method was called. @@ -1827,9 +1994,9 @@ async def test_delete_function_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_delete_function_flattened(): @@ -1838,15 +2005,13 @@ def test_delete_function_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + 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_function( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1854,7 +2019,7 @@ def test_delete_function_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -1868,9 +2033,10 @@ def test_delete_function_flattened_error(): with pytest.raises(ValueError): client.delete_function( functions.DeleteFunctionRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_function_flattened_async(): client = FunctionServiceAsyncClient( @@ -1878,19 +2044,17 @@ async def test_delete_function_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_function), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + 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_function( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1898,9 +2062,10 @@ async def test_delete_function_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_delete_function_flattened_error_async(): client = FunctionServiceAsyncClient( @@ -1912,15 +2077,18 @@ async def test_delete_function_flattened_error_async(): with pytest.raises(ValueError): await client.delete_function( functions.DeleteFunctionRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - functions.GenerateUploadUrlRequest, - dict, -]) -def test_generate_upload_url(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + functions.GenerateUploadUrlRequest, + dict, + ], +) +def test_generate_upload_url(request_type, transport: str = "grpc"): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1932,11 +2100,11 @@ def test_generate_upload_url(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: + type(client.transport.generate_upload_url), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = functions.GenerateUploadUrlResponse( - upload_url='upload_url_value', + upload_url="upload_url_value", ) response = client.generate_upload_url(request) @@ -1947,7 +2115,7 @@ def test_generate_upload_url(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, functions.GenerateUploadUrlResponse) - assert response.upload_url == 'upload_url_value' + assert response.upload_url == "upload_url_value" def test_generate_upload_url_empty_call(): @@ -1955,20 +2123,23 @@ def test_generate_upload_url_empty_call(): # i.e. request == None and no flattened fields passed, work. client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: + type(client.transport.generate_upload_url), "__call__" + ) as call: client.generate_upload_url() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == functions.GenerateUploadUrlRequest() + @pytest.mark.asyncio -async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateUploadUrlRequest): +async def test_generate_upload_url_async( + transport: str = "grpc_asyncio", request_type=functions.GenerateUploadUrlRequest +): client = FunctionServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1980,12 +2151,14 @@ async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', reques # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: + type(client.transport.generate_upload_url), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse( - upload_url='upload_url_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.GenerateUploadUrlResponse( + upload_url="upload_url_value", + ) + ) response = await client.generate_upload_url(request) # Establish that the underlying gRPC stub method was called. @@ -1995,7 +2168,7 @@ async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', reques # Establish that the response is the type that we expect. assert isinstance(response, functions.GenerateUploadUrlResponse) - assert response.upload_url == 'upload_url_value' + assert response.upload_url == "upload_url_value" @pytest.mark.asyncio @@ -2012,12 +2185,12 @@ def test_generate_upload_url_field_headers(): # a field header. Set these to a non-empty value. request = functions.GenerateUploadUrlRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: + type(client.transport.generate_upload_url), "__call__" + ) as call: call.return_value = functions.GenerateUploadUrlResponse() client.generate_upload_url(request) @@ -2029,9 +2202,9 @@ def test_generate_upload_url_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2044,13 +2217,15 @@ async def test_generate_upload_url_field_headers_async(): # a field header. Set these to a non-empty value. request = functions.GenerateUploadUrlRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_upload_url), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateUploadUrlResponse()) + type(client.transport.generate_upload_url), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.GenerateUploadUrlResponse() + ) await client.generate_upload_url(request) # Establish that the underlying gRPC stub method was called. @@ -2061,16 +2236,19 @@ async def test_generate_upload_url_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -@pytest.mark.parametrize("request_type", [ - functions.GenerateDownloadUrlRequest, - dict, -]) -def test_generate_download_url(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + functions.GenerateDownloadUrlRequest, + dict, + ], +) +def test_generate_download_url(request_type, transport: str = "grpc"): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2082,11 +2260,11 @@ def test_generate_download_url(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: + type(client.transport.generate_download_url), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = functions.GenerateDownloadUrlResponse( - download_url='download_url_value', + download_url="download_url_value", ) response = client.generate_download_url(request) @@ -2097,7 +2275,7 @@ def test_generate_download_url(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, functions.GenerateDownloadUrlResponse) - assert response.download_url == 'download_url_value' + assert response.download_url == "download_url_value" def test_generate_download_url_empty_call(): @@ -2105,20 +2283,23 @@ def test_generate_download_url_empty_call(): # i.e. request == None and no flattened fields passed, work. client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: + type(client.transport.generate_download_url), "__call__" + ) as call: client.generate_download_url() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == functions.GenerateDownloadUrlRequest() + @pytest.mark.asyncio -async def test_generate_download_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateDownloadUrlRequest): +async def test_generate_download_url_async( + transport: str = "grpc_asyncio", request_type=functions.GenerateDownloadUrlRequest +): client = FunctionServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2130,12 +2311,14 @@ async def test_generate_download_url_async(transport: str = 'grpc_asyncio', requ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: + type(client.transport.generate_download_url), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse( - download_url='download_url_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.GenerateDownloadUrlResponse( + download_url="download_url_value", + ) + ) response = await client.generate_download_url(request) # Establish that the underlying gRPC stub method was called. @@ -2145,7 +2328,7 @@ async def test_generate_download_url_async(transport: str = 'grpc_asyncio', requ # Establish that the response is the type that we expect. assert isinstance(response, functions.GenerateDownloadUrlResponse) - assert response.download_url == 'download_url_value' + assert response.download_url == "download_url_value" @pytest.mark.asyncio @@ -2162,12 +2345,12 @@ def test_generate_download_url_field_headers(): # a field header. Set these to a non-empty value. request = functions.GenerateDownloadUrlRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: + type(client.transport.generate_download_url), "__call__" + ) as call: call.return_value = functions.GenerateDownloadUrlResponse() client.generate_download_url(request) @@ -2179,9 +2362,9 @@ def test_generate_download_url_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2194,13 +2377,15 @@ async def test_generate_download_url_field_headers_async(): # a field header. Set these to a non-empty value. request = functions.GenerateDownloadUrlRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_download_url), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.GenerateDownloadUrlResponse()) + type(client.transport.generate_download_url), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.GenerateDownloadUrlResponse() + ) await client.generate_download_url(request) # Establish that the underlying gRPC stub method was called. @@ -2211,16 +2396,19 @@ async def test_generate_download_url_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -@pytest.mark.parametrize("request_type", [ - functions.ListRuntimesRequest, - dict, -]) -def test_list_runtimes(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + functions.ListRuntimesRequest, + dict, + ], +) +def test_list_runtimes(request_type, transport: str = "grpc"): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2231,12 +2419,9 @@ def test_list_runtimes(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_runtimes), - '__call__') as call: + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = functions.ListRuntimesResponse( - ) + call.return_value = functions.ListRuntimesResponse() response = client.list_runtimes(request) # Establish that the underlying gRPC stub method was called. @@ -2253,20 +2438,21 @@ def test_list_runtimes_empty_call(): # i.e. request == None and no flattened fields passed, work. client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_runtimes), - '__call__') as call: + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: client.list_runtimes() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == functions.ListRuntimesRequest() + @pytest.mark.asyncio -async def test_list_runtimes_async(transport: str = 'grpc_asyncio', request_type=functions.ListRuntimesRequest): +async def test_list_runtimes_async( + transport: str = "grpc_asyncio", request_type=functions.ListRuntimesRequest +): client = FunctionServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2277,12 +2463,11 @@ async def test_list_runtimes_async(transport: str = 'grpc_asyncio', request_type request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_runtimes), - '__call__') as call: + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.ListRuntimesResponse( - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListRuntimesResponse() + ) response = await client.list_runtimes(request) # Establish that the underlying gRPC stub method was called. @@ -2308,12 +2493,10 @@ def test_list_runtimes_field_headers(): # a field header. Set these to a non-empty value. request = functions.ListRuntimesRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_runtimes), - '__call__') as call: + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: call.return_value = functions.ListRuntimesResponse() client.list_runtimes(request) @@ -2325,9 +2508,9 @@ def test_list_runtimes_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2340,13 +2523,13 @@ async def test_list_runtimes_field_headers_async(): # a field header. Set these to a non-empty value. request = functions.ListRuntimesRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_runtimes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListRuntimesResponse()) + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListRuntimesResponse() + ) await client.list_runtimes(request) # Establish that the underlying gRPC stub method was called. @@ -2357,9 +2540,9 @@ async def test_list_runtimes_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_list_runtimes_flattened(): @@ -2368,15 +2551,13 @@ def test_list_runtimes_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_runtimes), - '__call__') as call: + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = functions.ListRuntimesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_runtimes( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -2384,7 +2565,7 @@ def test_list_runtimes_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val @@ -2398,9 +2579,10 @@ def test_list_runtimes_flattened_error(): with pytest.raises(ValueError): client.list_runtimes( functions.ListRuntimesRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_runtimes_flattened_async(): client = FunctionServiceAsyncClient( @@ -2408,17 +2590,17 @@ async def test_list_runtimes_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_runtimes), - '__call__') as call: + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = functions.ListRuntimesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.ListRuntimesResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListRuntimesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_runtimes( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -2426,9 +2608,10 @@ async def test_list_runtimes_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val + @pytest.mark.asyncio async def test_list_runtimes_flattened_error_async(): client = FunctionServiceAsyncClient( @@ -2440,7 +2623,7 @@ async def test_list_runtimes_flattened_error_async(): with pytest.raises(ValueError): await client.list_runtimes( functions.ListRuntimesRequest(), - parent='parent_value', + parent="parent_value", ) @@ -2482,8 +2665,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = FunctionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() + client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -2505,6 +2687,7 @@ def test_transport_instance(): client = FunctionServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.FunctionServiceGrpcTransport( @@ -2519,26 +2702,35 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.FunctionServiceGrpcTransport, - transports.FunctionServiceGrpcAsyncIOTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + 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", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + ], +) def test_transport_kind(transport_name): transport = FunctionServiceClient.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 = FunctionServiceClient( @@ -2549,18 +2741,21 @@ def test_transport_grpc_default(): transports.FunctionServiceGrpcTransport, ) + def test_function_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.FunctionServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_function_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport.__init__') as Transport: + with mock.patch( + "google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.FunctionServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2569,20 +2764,20 @@ def test_function_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_function', - 'list_functions', - 'create_function', - 'update_function', - 'delete_function', - 'generate_upload_url', - 'generate_download_url', - 'list_runtimes', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'list_locations', - 'get_operation', - 'list_operations', + "get_function", + "list_functions", + "create_function", + "update_function", + "delete_function", + "generate_upload_url", + "generate_download_url", + "list_runtimes", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "list_locations", + "get_operation", + "list_operations", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2598,7 +2793,7 @@ def test_function_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2607,25 +2802,30 @@ def test_function_service_base_transport(): def test_function_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.FunctionServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + load_creds.assert_called_once_with( + "credentials.json", scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) def test_function_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.FunctionServiceTransport() @@ -2634,14 +2834,12 @@ def test_function_service_base_transport_with_adc(): def test_function_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) FunctionServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id=None, ) @@ -2656,12 +2854,12 @@ def test_function_service_auth_adc(): def test_function_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + 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',), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) @@ -2674,48 +2872,45 @@ def test_function_service_transport_auth_adc(transport_class): ], ) def test_function_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) adc.return_value = (gdch_mock, None) transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) + gdch_mock.with_gdch_audience.assert_called_once_with(e) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.FunctionServiceGrpcTransport, grpc_helpers), - (transports.FunctionServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.FunctionServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_function_service_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "cloudfunctions.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=["1", "2"], default_host="cloudfunctions.googleapis.com", ssl_credentials=None, @@ -2726,10 +2921,14 @@ def test_function_service_transport_create_channel(transport_class, grpc_helpers ) -@pytest.mark.parametrize("transport_class", [transports.FunctionServiceGrpcTransport, transports.FunctionServiceGrpcAsyncIOTransport]) -def test_function_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) +def test_function_service_grpc_transport_client_cert_source_for_mtls(transport_class): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -2738,7 +2937,7 @@ def test_function_service_grpc_transport_client_cert_source_for_mtls( transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -2759,45 +2958,52 @@ def test_function_service_grpc_transport_client_cert_source_for_mtls( with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + 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 + certificate_chain=expected_cert, private_key=expected_key ) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) def test_function_service_host_no_port(transport_name): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:443' + client_options=client_options.ClientOptions( + api_endpoint="cloudfunctions.googleapis.com" + ), + transport=transport_name, ) + assert client.transport._host == ("cloudfunctions.googleapis.com:443") + -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) def test_function_service_host_with_port(transport_name): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudfunctions.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="cloudfunctions.googleapis.com:8000" + ), transport=transport_name, ) - assert client.transport._host == ( - 'cloudfunctions.googleapis.com:8000' - ) + assert client.transport._host == ("cloudfunctions.googleapis.com:8000") + def test_function_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.FunctionServiceGrpcTransport( @@ -2810,7 +3016,7 @@ def test_function_service_grpc_transport_channel(): def test_function_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.FunctionServiceGrpcAsyncIOTransport( @@ -2824,12 +3030,22 @@ def test_function_service_grpc_asyncio_transport_channel(): # 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.FunctionServiceGrpcTransport, transports.FunctionServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) def test_function_service_transport_channel_mtls_with_client_cert_source( - transport_class + 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: + 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 @@ -2838,7 +3054,7 @@ def test_function_service_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2868,17 +3084,23 @@ def test_function_service_transport_channel_mtls_with_client_cert_source( # 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.FunctionServiceGrpcTransport, transports.FunctionServiceGrpcAsyncIOTransport]) -def test_function_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) +def test_function_service_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + 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() @@ -2909,7 +3131,7 @@ def test_function_service_transport_channel_mtls_with_adc( def test_function_service_grpc_lro_client(): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -2926,7 +3148,7 @@ def test_function_service_grpc_lro_client(): def test_function_service_grpc_lro_async_client(): client = FunctionServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', + transport="grpc_asyncio", ) transport = client.transport @@ -2944,7 +3166,11 @@ def test_build_path(): project = "squid" location = "clam" build = "whelk" - expected = "projects/{project}/locations/{location}/builds/{build}".format(project=project, location=location, build=build, ) + expected = "projects/{project}/locations/{location}/builds/{build}".format( + project=project, + location=location, + build=build, + ) actual = FunctionServiceClient.build_path(project, location, build) assert expected == actual @@ -2961,11 +3187,16 @@ def test_parse_build_path(): actual = FunctionServiceClient.parse_build_path(path) assert expected == actual + def test_channel_path(): project = "cuttlefish" location = "mussel" channel = "winkle" - expected = "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) + expected = "projects/{project}/locations/{location}/channels/{channel}".format( + project=project, + location=location, + channel=channel, + ) actual = FunctionServiceClient.channel_path(project, location, channel) assert expected == actual @@ -2982,11 +3213,16 @@ def test_parse_channel_path(): actual = FunctionServiceClient.parse_channel_path(path) assert expected == actual + def test_connector_path(): project = "squid" location = "clam" connector = "whelk" - expected = "projects/{project}/locations/{location}/connectors/{connector}".format(project=project, location=location, connector=connector, ) + expected = "projects/{project}/locations/{location}/connectors/{connector}".format( + project=project, + location=location, + connector=connector, + ) actual = FunctionServiceClient.connector_path(project, location, connector) assert expected == actual @@ -3003,11 +3239,16 @@ def test_parse_connector_path(): actual = FunctionServiceClient.parse_connector_path(path) assert expected == actual + def test_function_path(): project = "cuttlefish" location = "mussel" function = "winkle" - expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + expected = "projects/{project}/locations/{location}/functions/{function}".format( + project=project, + location=location, + function=function, + ) actual = FunctionServiceClient.function_path(project, location, function) assert expected == actual @@ -3024,11 +3265,18 @@ def test_parse_function_path(): actual = FunctionServiceClient.parse_function_path(path) assert expected == actual + def test_repository_path(): project = "squid" location = "clam" repository = "whelk" - expected = "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) + expected = ( + "projects/{project}/locations/{location}/repositories/{repository}".format( + project=project, + location=location, + repository=repository, + ) + ) actual = FunctionServiceClient.repository_path(project, location, repository) assert expected == actual @@ -3045,11 +3293,16 @@ def test_parse_repository_path(): actual = FunctionServiceClient.parse_repository_path(path) assert expected == actual + def test_service_path(): project = "cuttlefish" location = "mussel" service = "winkle" - expected = "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) + expected = "projects/{project}/locations/{location}/services/{service}".format( + project=project, + location=location, + service=service, + ) actual = FunctionServiceClient.service_path(project, location, service) assert expected == actual @@ -3066,10 +3319,14 @@ def test_parse_service_path(): actual = FunctionServiceClient.parse_service_path(path) assert expected == actual + def test_topic_path(): project = "squid" topic = "clam" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + expected = "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) actual = FunctionServiceClient.topic_path(project, topic) assert expected == actual @@ -3085,11 +3342,16 @@ def test_parse_topic_path(): actual = FunctionServiceClient.parse_topic_path(path) assert expected == actual + def test_trigger_path(): project = "oyster" location = "nudibranch" trigger = "cuttlefish" - expected = "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) + expected = "projects/{project}/locations/{location}/triggers/{trigger}".format( + project=project, + location=location, + trigger=trigger, + ) actual = FunctionServiceClient.trigger_path(project, location, trigger) assert expected == actual @@ -3106,11 +3368,18 @@ def test_parse_trigger_path(): actual = FunctionServiceClient.parse_trigger_path(path) assert expected == actual + def test_worker_pool_path(): project = "scallop" location = "abalone" worker_pool = "squid" - expected = "projects/{project}/locations/{location}/workerPools/{worker_pool}".format(project=project, location=location, worker_pool=worker_pool, ) + expected = ( + "projects/{project}/locations/{location}/workerPools/{worker_pool}".format( + project=project, + location=location, + worker_pool=worker_pool, + ) + ) actual = FunctionServiceClient.worker_pool_path(project, location, worker_pool) assert expected == actual @@ -3127,9 +3396,12 @@ def test_parse_worker_pool_path(): actual = FunctionServiceClient.parse_worker_pool_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = FunctionServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -3144,9 +3416,12 @@ def test_parse_common_billing_account_path(): actual = FunctionServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = FunctionServiceClient.common_folder_path(folder) assert expected == actual @@ -3161,9 +3436,12 @@ def test_parse_common_folder_path(): actual = FunctionServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = FunctionServiceClient.common_organization_path(organization) assert expected == actual @@ -3178,9 +3456,12 @@ def test_parse_common_organization_path(): actual = FunctionServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = FunctionServiceClient.common_project_path(project) assert expected == actual @@ -3195,10 +3476,14 @@ def test_parse_common_project_path(): actual = FunctionServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = FunctionServiceClient.common_location_path(project, location) assert expected == actual @@ -3218,14 +3503,18 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.FunctionServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.FunctionServiceTransport, "_prep_wrapped_messages" + ) as prep: client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.FunctionServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.FunctionServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = FunctionServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -3233,13 +3522,16 @@ def test_client_with_default_client_info(): ) prep.assert_called_once_with(client_info) + @pytest.mark.asyncio async def test_transport_close_async(): client = FunctionServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: async with client: close.assert_not_called() close.assert_called_once() @@ -3247,7 +3539,8 @@ async def test_transport_close_async(): def test_get_operation(transport: str = "grpc"): client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3266,10 +3559,13 @@ def test_get_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) + + @pytest.mark.asyncio async def test_get_operation(transport: str = "grpc"): client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3291,6 +3587,7 @@ async def test_get_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) + def test_get_operation_field_headers(): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3313,7 +3610,12 @@ def test_get_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = FunctionServiceAsyncClient( @@ -3338,7 +3640,11 @@ async def test_get_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_get_operation_from_dict(): client = FunctionServiceClient( @@ -3355,6 +3661,8 @@ def test_get_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = FunctionServiceAsyncClient( @@ -3376,7 +3684,8 @@ async def test_get_operation_from_dict_async(): def test_list_operations(transport: str = "grpc"): client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3395,10 +3704,13 @@ def test_list_operations(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + + @pytest.mark.asyncio async def test_list_operations(transport: str = "grpc"): client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3420,6 +3732,7 @@ async def test_list_operations(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + def test_list_operations_field_headers(): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3442,7 +3755,12 @@ def test_list_operations_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = FunctionServiceAsyncClient( @@ -3467,7 +3785,11 @@ async def test_list_operations_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_list_operations_from_dict(): client = FunctionServiceClient( @@ -3484,6 +3806,8 @@ def test_list_operations_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = FunctionServiceAsyncClient( @@ -3505,7 +3829,8 @@ async def test_list_operations_from_dict_async(): def test_list_locations(transport: str = "grpc"): client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3524,10 +3849,13 @@ def test_list_locations(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.ListLocationsResponse) + + @pytest.mark.asyncio async def test_list_locations(transport: str = "grpc"): client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3549,6 +3877,7 @@ async def test_list_locations(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.ListLocationsResponse) + def test_list_locations_field_headers(): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3571,7 +3900,12 @@ def test_list_locations_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = FunctionServiceAsyncClient( @@ -3596,7 +3930,11 @@ async def test_list_locations_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_list_locations_from_dict(): client = FunctionServiceClient( @@ -3613,6 +3951,8 @@ def test_list_locations_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = FunctionServiceAsyncClient( @@ -3634,7 +3974,8 @@ async def test_list_locations_from_dict_async(): def test_set_iam_policy(transport: str = "grpc"): client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3644,7 +3985,10 @@ def test_set_iam_policy(transport: str = "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: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + 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 @@ -3658,10 +4002,13 @@ def test_set_iam_policy(transport: str = "grpc"): assert response.version == 774 assert response.etag == b"etag_blob" + + @pytest.mark.asyncio async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3673,7 +4020,10 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): # Designate an appropriate return value for the call. # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) + 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. @@ -3689,6 +4039,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" + def test_set_iam_policy_field_headers(): client = FunctionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3712,7 +4063,12 @@ def test_set_iam_policy_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = FunctionServiceAsyncClient( @@ -3737,7 +4093,11 @@ async def test_set_iam_policy_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + def test_set_iam_policy_from_dict(): client = FunctionServiceClient( @@ -3765,9 +4125,7 @@ async def test_set_iam_policy_from_dict_async(): # 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() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.set_iam_policy( request={ @@ -3777,9 +4135,11 @@ async def test_set_iam_policy_from_dict_async(): ) call.assert_called() + def test_get_iam_policy(transport: str = "grpc"): client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3789,7 +4149,10 @@ def test_get_iam_policy(transport: str = "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: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) response = client.get_iam_policy(request) @@ -3810,7 +4173,8 @@ def test_get_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3818,12 +4182,13 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): request = iam_policy_pb2.GetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: + 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",) + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) ) response = await client.get_iam_policy(request) @@ -3865,7 +4230,10 @@ def test_get_iam_policy_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -3880,9 +4248,7 @@ async def test_get_iam_policy_field_headers_async(): 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: + 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) @@ -3894,7 +4260,10 @@ async def test_get_iam_policy_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] def test_get_iam_policy_from_dict(): @@ -3914,6 +4283,7 @@ def test_get_iam_policy_from_dict(): ) call.assert_called() + @pytest.mark.asyncio async def test_get_iam_policy_from_dict_async(): client = FunctionServiceAsyncClient( @@ -3922,9 +4292,7 @@ async def test_get_iam_policy_from_dict_async(): # 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() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.get_iam_policy( request={ @@ -3934,9 +4302,11 @@ async def test_get_iam_policy_from_dict_async(): ) call.assert_called() + def test_test_iam_permissions(transport: str = "grpc"): client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3969,7 +4339,8 @@ def test_test_iam_permissions(transport: str = "grpc"): @pytest.mark.asyncio async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3982,7 +4353,9 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) response = await client.test_iam_permissions(request) @@ -4024,7 +4397,10 @@ def test_test_iam_permissions_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -4055,7 +4431,10 @@ async def test_test_iam_permissions_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] def test_test_iam_permissions_from_dict(): @@ -4077,6 +4456,7 @@ def test_test_iam_permissions_from_dict(): ) call.assert_called() + @pytest.mark.asyncio async def test_test_iam_permissions_from_dict_async(): client = FunctionServiceAsyncClient( @@ -4099,6 +4479,7 @@ async def test_test_iam_permissions_from_dict_async(): ) call.assert_called() + def test_transport_close(): transports = { "grpc": "_grpc_channel", @@ -4106,22 +4487,23 @@ def test_transport_close(): for transport, close_name in transports.items(): client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + 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', + "grpc", ] for transport in transports: client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -4130,10 +4512,14 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (FunctionServiceClient, transports.FunctionServiceGrpcTransport), - (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport), + (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True From c63fef32e7c4d4a4e992af2c1f26a2d9b507177f Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 7 Jul 2022 16:22:35 +0000 Subject: [PATCH 07/16] fix(deps): require google-api-core 2.8.0 --- setup.py | 5 +---- testing/constraints-3.6.txt | 11 ----------- testing/constraints-3.7.txt | 2 +- 3 files changed, 2 insertions(+), 16 deletions(-) delete mode 100644 testing/constraints-3.6.txt diff --git a/setup.py b/setup.py index 0e3204e..329f465 100644 --- a/setup.py +++ b/setup.py @@ -46,10 +46,7 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - # NOTE: Maintainers, please do not require google-api-core>=2.x.x - # Until this issue is closed - # https://github.com/googleapis/google-cloud-python/issues/10566 - "google-api-core[grpc] >= 1.31.5, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0", + "google-api-core[grpc] >= 2.8.0, <3.0.0dev", "proto-plus >= 1.15.0, <2.0.0dev", "protobuf >= 3.19.0, <4.0.0dev", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt deleted file mode 100644 index 60b7a7a..0000000 --- a/testing/constraints-3.6.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List *all* library dependencies and extras in this file. -# Pin the version to the lower bound. -# -# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", -# Then this file should have foo==1.14.0 -google-api-core==1.31.5 -proto-plus==1.15.0 -grpc-google-iam-v1==0.12.4 -protobuf==3.19.0 diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 60b7a7a..87b0026 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -5,7 +5,7 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-api-core==1.31.5 +google-api-core==2.8.0 proto-plus==1.15.0 grpc-google-iam-v1==0.12.4 protobuf==3.19.0 From 9ab093b12e767a96c46a0e08614638ad63a1c860 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 14 Jul 2022 12:32:05 +0000 Subject: [PATCH 08/16] fix(deps): require google-api-core>=1.32.0,>=2.8.0 --- setup.py | 2 +- testing/constraints-3.7.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 400f9c1..99f6b7f 100644 --- a/setup.py +++ b/setup.py @@ -46,7 +46,7 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - "google-api-core[grpc] >= 2.8.0, <3.0.0dev", + "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", "proto-plus >= 1.15.0, <2.0.0dev", "protobuf >= 3.19.0, <4.0.0dev", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 87b0026..f9ec620 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -5,7 +5,7 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-api-core==2.8.0 +google-api-core==1.32.0 proto-plus==1.15.0 grpc-google-iam-v1==0.12.4 protobuf==3.19.0 From 0f522d3992e21f7b981b3ab6011112f49a8a17dc Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 14 Jul 2022 12:40:18 +0000 Subject: [PATCH 09/16] chore: add workaround in owlbot.py to fix docs build --- .github/release-please.yml | 6 -- docs/conf.py | 2 +- google/cloud/functions/__init__.py | 89 ++++++++++--------- google/cloud/functions_v2/__init__.py | 60 ++++++------- .../services/function_service/__init__.py | 2 +- .../services/function_service/async_client.py | 36 +++++--- .../services/function_service/client.py | 34 ++++--- .../services/function_service/pagers.py | 4 +- .../function_service/transports/__init__.py | 1 + .../function_service/transports/base.py | 14 +-- .../function_service/transports/grpc.py | 17 ++-- .../transports/grpc_asyncio.py | 19 ++-- google/cloud/functions_v2/types/__init__.py | 2 +- google/cloud/functions_v2/types/functions.py | 4 +- owlbot.py | 73 +++++++++++++++ .../functions_v2/test_function_service.py | 42 +++++---- 16 files changed, 252 insertions(+), 153 deletions(-) create mode 100644 owlbot.py diff --git a/.github/release-please.yml b/.github/release-please.yml index 6def37a..466597e 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1,8 +1,2 @@ releaseType: python handleGHRelease: true -# NOTE: this section is generated by synthtool.languages.python -# See https://github.com/googleapis/synthtool/blob/master/synthtool/languages/python.py -branches: -- branch: v0 - handleGHRelease: true - releaseType: python diff --git a/docs/conf.py b/docs/conf.py index a4b6149..d0098f3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -24,9 +24,9 @@ # All configuration values have a default; values that are commented out # serve to show the default. +import sys import os import shlex -import sys # 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 diff --git a/google/cloud/functions/__init__.py b/google/cloud/functions/__init__.py index e17aeb3..eb5e567 100644 --- a/google/cloud/functions/__init__.py +++ b/google/cloud/functions/__init__.py @@ -14,62 +14,69 @@ # limitations under the License. # -from google.cloud.functions_v1.services.cloud_functions_service.async_client import ( - CloudFunctionsServiceAsyncClient, +from google.cloud.functions_v2.services.function_service.client import ( + FunctionServiceClient, ) -from google.cloud.functions_v1.services.cloud_functions_service.client import ( - CloudFunctionsServiceClient, -) -from google.cloud.functions_v1.types.functions import ( - CallFunctionRequest, - CallFunctionResponse, - CloudFunction, - CloudFunctionStatus, - CreateFunctionRequest, - DeleteFunctionRequest, - EventTrigger, - FailurePolicy, - GenerateDownloadUrlRequest, - GenerateDownloadUrlResponse, - GenerateUploadUrlRequest, - GenerateUploadUrlResponse, - GetFunctionRequest, - HttpsTrigger, - ListFunctionsRequest, - ListFunctionsResponse, - SecretEnvVar, - SecretVolume, - SourceRepository, - UpdateFunctionRequest, -) -from google.cloud.functions_v1.types.operations import ( - OperationMetadataV1, - OperationType, +from google.cloud.functions_v2.services.function_service.async_client import ( + FunctionServiceAsyncClient, ) +from google.cloud.functions_v2.types.functions import BuildConfig +from google.cloud.functions_v2.types.functions import CreateFunctionRequest +from google.cloud.functions_v2.types.functions import DeleteFunctionRequest +from google.cloud.functions_v2.types.functions import EventFilter +from google.cloud.functions_v2.types.functions import EventTrigger +from google.cloud.functions_v2.types.functions import Function +from google.cloud.functions_v2.types.functions import GenerateDownloadUrlRequest +from google.cloud.functions_v2.types.functions import GenerateDownloadUrlResponse +from google.cloud.functions_v2.types.functions import GenerateUploadUrlRequest +from google.cloud.functions_v2.types.functions import GenerateUploadUrlResponse +from google.cloud.functions_v2.types.functions import GetFunctionRequest +from google.cloud.functions_v2.types.functions import ListFunctionsRequest +from google.cloud.functions_v2.types.functions import ListFunctionsResponse +from google.cloud.functions_v2.types.functions import ListRuntimesRequest +from google.cloud.functions_v2.types.functions import ListRuntimesResponse +from google.cloud.functions_v2.types.functions import OperationMetadata +from google.cloud.functions_v2.types.functions import RepoSource +from google.cloud.functions_v2.types.functions import SecretEnvVar +from google.cloud.functions_v2.types.functions import SecretVolume +from google.cloud.functions_v2.types.functions import ServiceConfig +from google.cloud.functions_v2.types.functions import Source +from google.cloud.functions_v2.types.functions import SourceProvenance +from google.cloud.functions_v2.types.functions import Stage +from google.cloud.functions_v2.types.functions import StateMessage +from google.cloud.functions_v2.types.functions import StorageSource +from google.cloud.functions_v2.types.functions import UpdateFunctionRequest +from google.cloud.functions_v2.types.functions import Environment + __all__ = ( - "CloudFunctionsServiceClient", - "CloudFunctionsServiceAsyncClient", - "CallFunctionRequest", - "CallFunctionResponse", - "CloudFunction", + "FunctionServiceClient", + "FunctionServiceAsyncClient", + "BuildConfig", "CreateFunctionRequest", "DeleteFunctionRequest", + "EventFilter", "EventTrigger", - "FailurePolicy", + "Function", "GenerateDownloadUrlRequest", "GenerateDownloadUrlResponse", "GenerateUploadUrlRequest", "GenerateUploadUrlResponse", "GetFunctionRequest", - "HttpsTrigger", "ListFunctionsRequest", "ListFunctionsResponse", + "ListRuntimesRequest", + "ListRuntimesResponse", + "OperationMetadata", + "RepoSource", "SecretEnvVar", "SecretVolume", - "SourceRepository", + "ServiceConfig", + "Source", + "SourceProvenance", + "Stage", + "StateMessage", + "StorageSource", "UpdateFunctionRequest", - "CloudFunctionStatus", - "OperationMetadataV1", - "OperationType", + "Environment", ) diff --git a/google/cloud/functions_v2/__init__.py b/google/cloud/functions_v2/__init__.py index 8810a81..3e412cb 100644 --- a/google/cloud/functions_v2/__init__.py +++ b/google/cloud/functions_v2/__init__.py @@ -14,36 +14,36 @@ # limitations under the License. # -from .services.function_service import FunctionServiceAsyncClient, FunctionServiceClient -from .types.functions import ( - BuildConfig, - CreateFunctionRequest, - DeleteFunctionRequest, - Environment, - EventFilter, - EventTrigger, - Function, - GenerateDownloadUrlRequest, - GenerateDownloadUrlResponse, - GenerateUploadUrlRequest, - GenerateUploadUrlResponse, - GetFunctionRequest, - ListFunctionsRequest, - ListFunctionsResponse, - ListRuntimesRequest, - ListRuntimesResponse, - OperationMetadata, - RepoSource, - SecretEnvVar, - SecretVolume, - ServiceConfig, - Source, - SourceProvenance, - Stage, - StateMessage, - StorageSource, - UpdateFunctionRequest, -) +from .services.function_service import FunctionServiceClient +from .services.function_service import FunctionServiceAsyncClient + +from .types.functions import BuildConfig +from .types.functions import CreateFunctionRequest +from .types.functions import DeleteFunctionRequest +from .types.functions import EventFilter +from .types.functions import EventTrigger +from .types.functions import Function +from .types.functions import GenerateDownloadUrlRequest +from .types.functions import GenerateDownloadUrlResponse +from .types.functions import GenerateUploadUrlRequest +from .types.functions import GenerateUploadUrlResponse +from .types.functions import GetFunctionRequest +from .types.functions import ListFunctionsRequest +from .types.functions import ListFunctionsResponse +from .types.functions import ListRuntimesRequest +from .types.functions import ListRuntimesResponse +from .types.functions import OperationMetadata +from .types.functions import RepoSource +from .types.functions import SecretEnvVar +from .types.functions import SecretVolume +from .types.functions import ServiceConfig +from .types.functions import Source +from .types.functions import SourceProvenance +from .types.functions import Stage +from .types.functions import StateMessage +from .types.functions import StorageSource +from .types.functions import UpdateFunctionRequest +from .types.functions import Environment __all__ = ( "FunctionServiceAsyncClient", diff --git a/google/cloud/functions_v2/services/function_service/__init__.py b/google/cloud/functions_v2/services/function_service/__init__.py index 73f00d9..cc54d98 100644 --- a/google/cloud/functions_v2/services/function_service/__init__.py +++ b/google/cloud/functions_v2/services/function_service/__init__.py @@ -13,8 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .async_client import FunctionServiceAsyncClient from .client import FunctionServiceClient +from .async_client import FunctionServiceAsyncClient __all__ = ( "FunctionServiceClient", diff --git a/google/cloud/functions_v2/services/function_service/async_client.py b/google/cloud/functions_v2/services/function_service/async_client.py index 70a1568..8f53cc6 100644 --- a/google/cloud/functions_v2/services/function_service/async_client.py +++ b/google/cloud/functions_v2/services/function_service/async_client.py @@ -17,14 +17,14 @@ 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.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -import pkg_resources try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -33,6 +33,8 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.types import functions from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore @@ -40,13 +42,9 @@ from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore - -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.types import functions - -from .client import FunctionServiceClient -from .transports.base import DEFAULT_CLIENT_INFO, FunctionServiceTransport +from .transports.base import FunctionServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport +from .client import FunctionServiceClient class FunctionServiceAsyncClient: @@ -1237,9 +1235,10 @@ async def set_iam_policy( 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** - :: + resource. JSON Example. + + .. code-block:: python + { "bindings": [ { @@ -1263,8 +1262,11 @@ async def set_iam_policy( } ] } + **YAML Example** + :: + bindings: - members: - user:mike@example.com @@ -1279,6 +1281,7 @@ async def set_iam_policy( title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM developer's guide `__. @@ -1351,9 +1354,10 @@ async def get_iam_policy( 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** - :: + resource. JSON Example. + + .. code-block:: python + { "bindings": [ { @@ -1377,8 +1381,11 @@ async def get_iam_policy( } ] } + **YAML Example** + :: + bindings: - members: - user:mike@example.com @@ -1393,6 +1400,7 @@ async def get_iam_policy( title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM developer's guide `__. diff --git a/google/cloud/functions_v2/services/function_service/client.py b/google/cloud/functions_v2/services/function_service/client.py index e4e6484..f6c2a2b 100644 --- a/google/cloud/functions_v2/services/function_service/client.py +++ b/google/cloud/functions_v2/services/function_service/client.py @@ -17,17 +17,17 @@ 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.exceptions import MutualTLSChannelError # 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 -import pkg_resources try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -36,6 +36,8 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.types import functions from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore @@ -43,11 +45,7 @@ from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore - -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.types import functions - -from .transports.base import DEFAULT_CLIENT_INFO, FunctionServiceTransport +from .transports.base import FunctionServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import FunctionServiceGrpcTransport from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport @@ -1636,9 +1634,10 @@ def set_iam_policy( 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** - :: + resource. JSON Example. + + .. code-block:: python + { "bindings": [ { @@ -1662,8 +1661,11 @@ def set_iam_policy( } ] } + **YAML Example** + :: + bindings: - members: - user:mike@example.com @@ -1678,6 +1680,7 @@ def set_iam_policy( title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM developer's guide `__. @@ -1750,9 +1753,10 @@ def get_iam_policy( 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** - :: + resource. JSON Example. + + .. code-block:: python + { "bindings": [ { @@ -1776,8 +1780,11 @@ def get_iam_policy( } ] } + **YAML Example** + :: + bindings: - members: - user:mike@example.com @@ -1792,6 +1799,7 @@ def get_iam_policy( title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM developer's guide `__. diff --git a/google/cloud/functions_v2/services/function_service/pagers.py b/google/cloud/functions_v2/services/function_service/pagers.py index 08de657..4d18992 100644 --- a/google/cloud/functions_v2/services/function_service/pagers.py +++ b/google/cloud/functions_v2/services/function_service/pagers.py @@ -18,10 +18,10 @@ AsyncIterator, Awaitable, Callable, - Iterator, - Optional, Sequence, Tuple, + Optional, + Iterator, ) from google.cloud.functions_v2.types import functions diff --git a/google/cloud/functions_v2/services/function_service/transports/__init__.py b/google/cloud/functions_v2/services/function_service/transports/__init__.py index cc0b207..31e8292 100644 --- a/google/cloud/functions_v2/services/function_service/transports/__init__.py +++ b/google/cloud/functions_v2/services/function_service/transports/__init__.py @@ -20,6 +20,7 @@ from .grpc import FunctionServiceGrpcTransport from .grpc_asyncio import FunctionServiceGrpcAsyncIOTransport + # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[FunctionServiceTransport]] _transport_registry["grpc"] = FunctionServiceGrpcTransport diff --git a/google/cloud/functions_v2/services/function_service/transports/base.py b/google/cloud/functions_v2/services/function_service/transports/base.py index ab49afa..33a06f4 100644 --- a/google/cloud/functions_v2/services/function_service/transports/base.py +++ b/google/cloud/functions_v2/services/function_service/transports/base.py @@ -15,21 +15,23 @@ # 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, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries -import google.auth # type: ignore +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.functions_v2.types import functions from google.cloud.location import locations_pb2 # type: ignore 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 from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore -import pkg_resources - -from google.cloud.functions_v2.types import functions try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/functions_v2/services/function_service/transports/grpc.py b/google/cloud/functions_v2/services/function_service/transports/grpc.py index 668762f..b4ea1ed 100644 --- a/google/cloud/functions_v2/services/function_service/transports/grpc.py +++ b/google/cloud/functions_v2/services/function_service/transports/grpc.py @@ -13,22 +13,25 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, grpc_helpers, operations_v1 +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.functions_v2.types import functions from google.cloud.location import locations_pb2 # type: ignore 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 from google.longrunning import operations_pb2 # type: ignore -import grpc # type: ignore - -from google.cloud.functions_v2.types import functions - -from .base import DEFAULT_CLIENT_INFO, FunctionServiceTransport +from .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO class FunctionServiceGrpcTransport(FunctionServiceTransport): diff --git a/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py b/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py index 013f594..dbfe68e 100644 --- a/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py +++ b/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py @@ -13,22 +13,25 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +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 -from google.cloud.location import locations_pb2 # type: ignore -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 + import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.functions_v2.types import functions - -from .base import DEFAULT_CLIENT_INFO, FunctionServiceTransport +from google.cloud.location import locations_pb2 # type: ignore +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 +from google.longrunning import operations_pb2 # type: ignore +from .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO from .grpc import FunctionServiceGrpcTransport diff --git a/google/cloud/functions_v2/types/__init__.py b/google/cloud/functions_v2/types/__init__.py index 82a10a9..8132c59 100644 --- a/google/cloud/functions_v2/types/__init__.py +++ b/google/cloud/functions_v2/types/__init__.py @@ -17,7 +17,6 @@ BuildConfig, CreateFunctionRequest, DeleteFunctionRequest, - Environment, EventFilter, EventTrigger, Function, @@ -41,6 +40,7 @@ StateMessage, StorageSource, UpdateFunctionRequest, + Environment, ) __all__ = ( diff --git a/google/cloud/functions_v2/types/functions.py b/google/cloud/functions_v2/types/functions.py index 04435fb..81d1d43 100644 --- a/google/cloud/functions_v2/types/functions.py +++ b/google/cloud/functions_v2/types/functions.py @@ -13,10 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import proto # type: ignore + from google.protobuf import any_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore + __protobuf__ = proto.module( package="google.cloud.functions.v2", diff --git a/owlbot.py b/owlbot.py new file mode 100644 index 0000000..11c9002 --- /dev/null +++ b/owlbot.py @@ -0,0 +1,73 @@ +# 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 pathlib import Path + +import synthtool as s +import synthtool.gcp as gcp +from synthtool.languages import python + +# ---------------------------------------------------------------------------- +# Copy the generated client from the owl-bot staging directory +# ---------------------------------------------------------------------------- + +default_version = "v1" + +for library in s.get_staging_dirs(default_version): + # work around issues with docstrings + s.replace( + library / "google/cloud/**/*.py", + """resource. + \*\*JSON Example\*\* + ::""", + """resource. JSON Example. + + .. code-block:: python\n""", + ) + + s.replace( + library / "google/cloud/**/*.py", + """\*\*YAML Example\*\* + ::""", + """\n **YAML Example** + + ::\n""", + ) + + s.replace(library / "google/cloud/**/*.py", + """ For a description of IAM and its features, see the `IAM + developer's""", + """\n For a description of IAM and its features, see the `IAM + developer's""" + ) + s.move(library, excludes=["setup.py"]) +mnan +s.remove_staging_dirs() + +# ---------------------------------------------------------------------------- +# Add templated files +# ---------------------------------------------------------------------------- + +templated_files = gcp.CommonTemplates().py_library( + microgenerator=True, + versions=gcp.common.detect_versions(path="./google", default_first=True), +) +s.move(templated_files, excludes=[".coveragerc"]) # the microgenerator has a good coveragerc file + +python.py_samples(skip_readmes=True) + + +# run blacken session for all directories which have a noxfile +for noxfile in Path(".").glob("**/noxfile.py"): + s.shell.run(["nox", "-s", "blacken"], cwd=noxfile.parent, hide_output=False) diff --git a/tests/unit/gapic/functions_v2/test_function_service.py b/tests/unit/gapic/functions_v2/test_function_service.py index a28e59d..e98e3d9 100644 --- a/tests/unit/gapic/functions_v2/test_function_service.py +++ b/tests/unit/gapic/functions_v2/test_function_service.py @@ -22,23 +22,32 @@ except ImportError: import mock +import grpc +from grpc.experimental import aio import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + -from google.api_core import ( - future, - gapic_v1, - grpc_helpers, - grpc_helpers_async, - operation, - operations_v1, - path_template, -) 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 -import google.auth +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.functions_v2.services.function_service import ( + FunctionServiceAsyncClient, +) +from google.cloud.functions_v2.services.function_service import FunctionServiceClient +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.services.function_service import transports +from google.cloud.functions_v2.types import functions from google.cloud.location import locations_pb2 from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import options_pb2 # type: ignore @@ -47,18 +56,7 @@ from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -import grpc -from grpc.experimental import aio -from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest - -from google.cloud.functions_v2.services.function_service import ( - FunctionServiceAsyncClient, - FunctionServiceClient, - pagers, - transports, -) -from google.cloud.functions_v2.types import functions +import google.auth def client_cert_source_callback(): From 427876856ea31bea957d2bb4a9b4fc77ba1b5558 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 14 Jul 2022 12:41:56 +0000 Subject: [PATCH 10/16] restore changes in .github/release-please.yml --- .github/release-please.yml | 6 ++++++ owlbot.py | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/release-please.yml b/.github/release-please.yml index 466597e..6def37a 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1,2 +1,8 @@ releaseType: python handleGHRelease: true +# NOTE: this section is generated by synthtool.languages.python +# See https://github.com/googleapis/synthtool/blob/master/synthtool/languages/python.py +branches: +- branch: v0 + handleGHRelease: true + releaseType: python diff --git a/owlbot.py b/owlbot.py index 11c9002..ac4b413 100644 --- a/owlbot.py +++ b/owlbot.py @@ -52,7 +52,7 @@ developer's""" ) s.move(library, excludes=["setup.py"]) -mnan + s.remove_staging_dirs() # ---------------------------------------------------------------------------- @@ -65,6 +65,8 @@ ) s.move(templated_files, excludes=[".coveragerc"]) # the microgenerator has a good coveragerc file +python.configure_previous_major_version_branches() + python.py_samples(skip_readmes=True) From 4bcebf1cf36be2eabecab66e176a5b301d85a195 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 14 Jul 2022 12:43:15 +0000 Subject: [PATCH 11/16] update owlbot.py to reflect changes in main --- docs/conf.py | 2 +- google/cloud/functions/__init__.py | 61 ++++++++++--------- google/cloud/functions_v2/__init__.py | 60 +++++++++--------- .../services/function_service/__init__.py | 2 +- .../services/function_service/async_client.py | 14 +++-- .../services/function_service/client.py | 12 ++-- .../services/function_service/pagers.py | 4 +- .../function_service/transports/__init__.py | 1 - .../function_service/transports/base.py | 14 ++--- .../function_service/transports/grpc.py | 17 +++--- .../transports/grpc_asyncio.py | 19 +++--- google/cloud/functions_v2/types/__init__.py | 2 +- google/cloud/functions_v2/types/functions.py | 4 +- owlbot.py | 5 +- .../functions_v2/test_function_service.py | 42 +++++++------ 15 files changed, 127 insertions(+), 132 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index d0098f3..a4b6149 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -24,9 +24,9 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys import os import shlex +import sys # 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 diff --git a/google/cloud/functions/__init__.py b/google/cloud/functions/__init__.py index eb5e567..8300518 100644 --- a/google/cloud/functions/__init__.py +++ b/google/cloud/functions/__init__.py @@ -14,41 +14,42 @@ # limitations under the License. # +from google.cloud.functions_v2.services.function_service.async_client import ( + FunctionServiceAsyncClient, +) from google.cloud.functions_v2.services.function_service.client import ( FunctionServiceClient, ) -from google.cloud.functions_v2.services.function_service.async_client import ( - FunctionServiceAsyncClient, +from google.cloud.functions_v2.types.functions import ( + BuildConfig, + CreateFunctionRequest, + DeleteFunctionRequest, + Environment, + EventFilter, + EventTrigger, + Function, + GenerateDownloadUrlRequest, + GenerateDownloadUrlResponse, + GenerateUploadUrlRequest, + GenerateUploadUrlResponse, + GetFunctionRequest, + ListFunctionsRequest, + ListFunctionsResponse, + ListRuntimesRequest, + ListRuntimesResponse, + OperationMetadata, + RepoSource, + SecretEnvVar, + SecretVolume, + ServiceConfig, + Source, + SourceProvenance, + Stage, + StateMessage, + StorageSource, + UpdateFunctionRequest, ) -from google.cloud.functions_v2.types.functions import BuildConfig -from google.cloud.functions_v2.types.functions import CreateFunctionRequest -from google.cloud.functions_v2.types.functions import DeleteFunctionRequest -from google.cloud.functions_v2.types.functions import EventFilter -from google.cloud.functions_v2.types.functions import EventTrigger -from google.cloud.functions_v2.types.functions import Function -from google.cloud.functions_v2.types.functions import GenerateDownloadUrlRequest -from google.cloud.functions_v2.types.functions import GenerateDownloadUrlResponse -from google.cloud.functions_v2.types.functions import GenerateUploadUrlRequest -from google.cloud.functions_v2.types.functions import GenerateUploadUrlResponse -from google.cloud.functions_v2.types.functions import GetFunctionRequest -from google.cloud.functions_v2.types.functions import ListFunctionsRequest -from google.cloud.functions_v2.types.functions import ListFunctionsResponse -from google.cloud.functions_v2.types.functions import ListRuntimesRequest -from google.cloud.functions_v2.types.functions import ListRuntimesResponse -from google.cloud.functions_v2.types.functions import OperationMetadata -from google.cloud.functions_v2.types.functions import RepoSource -from google.cloud.functions_v2.types.functions import SecretEnvVar -from google.cloud.functions_v2.types.functions import SecretVolume -from google.cloud.functions_v2.types.functions import ServiceConfig -from google.cloud.functions_v2.types.functions import Source -from google.cloud.functions_v2.types.functions import SourceProvenance -from google.cloud.functions_v2.types.functions import Stage -from google.cloud.functions_v2.types.functions import StateMessage -from google.cloud.functions_v2.types.functions import StorageSource -from google.cloud.functions_v2.types.functions import UpdateFunctionRequest -from google.cloud.functions_v2.types.functions import Environment - __all__ = ( "FunctionServiceClient", "FunctionServiceAsyncClient", diff --git a/google/cloud/functions_v2/__init__.py b/google/cloud/functions_v2/__init__.py index 3e412cb..8810a81 100644 --- a/google/cloud/functions_v2/__init__.py +++ b/google/cloud/functions_v2/__init__.py @@ -14,36 +14,36 @@ # limitations under the License. # -from .services.function_service import FunctionServiceClient -from .services.function_service import FunctionServiceAsyncClient - -from .types.functions import BuildConfig -from .types.functions import CreateFunctionRequest -from .types.functions import DeleteFunctionRequest -from .types.functions import EventFilter -from .types.functions import EventTrigger -from .types.functions import Function -from .types.functions import GenerateDownloadUrlRequest -from .types.functions import GenerateDownloadUrlResponse -from .types.functions import GenerateUploadUrlRequest -from .types.functions import GenerateUploadUrlResponse -from .types.functions import GetFunctionRequest -from .types.functions import ListFunctionsRequest -from .types.functions import ListFunctionsResponse -from .types.functions import ListRuntimesRequest -from .types.functions import ListRuntimesResponse -from .types.functions import OperationMetadata -from .types.functions import RepoSource -from .types.functions import SecretEnvVar -from .types.functions import SecretVolume -from .types.functions import ServiceConfig -from .types.functions import Source -from .types.functions import SourceProvenance -from .types.functions import Stage -from .types.functions import StateMessage -from .types.functions import StorageSource -from .types.functions import UpdateFunctionRequest -from .types.functions import Environment +from .services.function_service import FunctionServiceAsyncClient, FunctionServiceClient +from .types.functions import ( + BuildConfig, + CreateFunctionRequest, + DeleteFunctionRequest, + Environment, + EventFilter, + EventTrigger, + Function, + GenerateDownloadUrlRequest, + GenerateDownloadUrlResponse, + GenerateUploadUrlRequest, + GenerateUploadUrlResponse, + GetFunctionRequest, + ListFunctionsRequest, + ListFunctionsResponse, + ListRuntimesRequest, + ListRuntimesResponse, + OperationMetadata, + RepoSource, + SecretEnvVar, + SecretVolume, + ServiceConfig, + Source, + SourceProvenance, + Stage, + StateMessage, + StorageSource, + UpdateFunctionRequest, +) __all__ = ( "FunctionServiceAsyncClient", diff --git a/google/cloud/functions_v2/services/function_service/__init__.py b/google/cloud/functions_v2/services/function_service/__init__.py index cc54d98..73f00d9 100644 --- a/google/cloud/functions_v2/services/function_service/__init__.py +++ b/google/cloud/functions_v2/services/function_service/__init__.py @@ -13,8 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import FunctionServiceClient from .async_client import FunctionServiceAsyncClient +from .client import FunctionServiceClient __all__ = ( "FunctionServiceClient", diff --git a/google/cloud/functions_v2/services/function_service/async_client.py b/google/cloud/functions_v2/services/function_service/async_client.py index 8f53cc6..be01241 100644 --- a/google/cloud/functions_v2/services/function_service/async_client.py +++ b/google/cloud/functions_v2/services/function_service/async_client.py @@ -17,14 +17,14 @@ 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.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore +import pkg_resources try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -33,8 +33,6 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.types import functions from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore @@ -42,9 +40,13 @@ from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FunctionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport + +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.types import functions + from .client import FunctionServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, FunctionServiceTransport +from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport class FunctionServiceAsyncClient: diff --git a/google/cloud/functions_v2/services/function_service/client.py b/google/cloud/functions_v2/services/function_service/client.py index f6c2a2b..f09c5cb 100644 --- a/google/cloud/functions_v2/services/function_service/client.py +++ b/google/cloud/functions_v2/services/function_service/client.py @@ -17,17 +17,17 @@ 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.exceptions import MutualTLSChannelError # 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 +import pkg_resources try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -36,8 +36,6 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.types import functions from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore @@ -45,7 +43,11 @@ from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FunctionServiceTransport, DEFAULT_CLIENT_INFO + +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.types import functions + +from .transports.base import DEFAULT_CLIENT_INFO, FunctionServiceTransport from .transports.grpc import FunctionServiceGrpcTransport from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport diff --git a/google/cloud/functions_v2/services/function_service/pagers.py b/google/cloud/functions_v2/services/function_service/pagers.py index 4d18992..08de657 100644 --- a/google/cloud/functions_v2/services/function_service/pagers.py +++ b/google/cloud/functions_v2/services/function_service/pagers.py @@ -18,10 +18,10 @@ AsyncIterator, Awaitable, Callable, + Iterator, + Optional, Sequence, Tuple, - Optional, - Iterator, ) from google.cloud.functions_v2.types import functions diff --git a/google/cloud/functions_v2/services/function_service/transports/__init__.py b/google/cloud/functions_v2/services/function_service/transports/__init__.py index 31e8292..cc0b207 100644 --- a/google/cloud/functions_v2/services/function_service/transports/__init__.py +++ b/google/cloud/functions_v2/services/function_service/transports/__init__.py @@ -20,7 +20,6 @@ from .grpc import FunctionServiceGrpcTransport from .grpc_asyncio import FunctionServiceGrpcAsyncIOTransport - # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[FunctionServiceTransport]] _transport_registry["grpc"] = FunctionServiceGrpcTransport diff --git a/google/cloud/functions_v2/services/function_service/transports/base.py b/google/cloud/functions_v2/services/function_service/transports/base.py index 33a06f4..ab49afa 100644 --- a/google/cloud/functions_v2/services/function_service/transports/base.py +++ b/google/cloud/functions_v2/services/function_service/transports/base.py @@ -15,23 +15,21 @@ # 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 gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.functions_v2.types import functions from google.cloud.location import locations_pb2 # type: ignore 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 from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import pkg_resources + +from google.cloud.functions_v2.types import functions try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/functions_v2/services/function_service/transports/grpc.py b/google/cloud/functions_v2/services/function_service/transports/grpc.py index b4ea1ed..668762f 100644 --- a/google/cloud/functions_v2/services/function_service/transports/grpc.py +++ b/google/cloud/functions_v2/services/function_service/transports/grpc.py @@ -13,25 +13,22 @@ # 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 +import warnings -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, grpc_helpers, operations_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.functions_v2.types import functions from google.cloud.location import locations_pb2 # type: ignore 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 from google.longrunning import operations_pb2 # type: ignore -from .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO +import grpc # type: ignore + +from google.cloud.functions_v2.types import functions + +from .base import DEFAULT_CLIENT_INFO, FunctionServiceTransport class FunctionServiceGrpcTransport(FunctionServiceTransport): diff --git a/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py b/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py index dbfe68e..013f594 100644 --- a/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py +++ b/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py @@ -13,25 +13,22 @@ # 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 +import warnings -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 +from google.api_core import gapic_v1, grpc_helpers_async, 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.functions_v2.types import functions from google.cloud.location import locations_pb2 # type: ignore 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 from google.longrunning import operations_pb2 # type: ignore -from .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.functions_v2.types import functions + +from .base import DEFAULT_CLIENT_INFO, FunctionServiceTransport from .grpc import FunctionServiceGrpcTransport diff --git a/google/cloud/functions_v2/types/__init__.py b/google/cloud/functions_v2/types/__init__.py index 8132c59..82a10a9 100644 --- a/google/cloud/functions_v2/types/__init__.py +++ b/google/cloud/functions_v2/types/__init__.py @@ -17,6 +17,7 @@ BuildConfig, CreateFunctionRequest, DeleteFunctionRequest, + Environment, EventFilter, EventTrigger, Function, @@ -40,7 +41,6 @@ StateMessage, StorageSource, UpdateFunctionRequest, - Environment, ) __all__ = ( diff --git a/google/cloud/functions_v2/types/functions.py b/google/cloud/functions_v2/types/functions.py index 81d1d43..04435fb 100644 --- a/google/cloud/functions_v2/types/functions.py +++ b/google/cloud/functions_v2/types/functions.py @@ -13,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import proto # type: ignore - from google.protobuf import any_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.functions.v2", diff --git a/owlbot.py b/owlbot.py index ac4b413..5629e2e 100644 --- a/owlbot.py +++ b/owlbot.py @@ -69,7 +69,6 @@ python.py_samples(skip_readmes=True) - -# run blacken session for all directories which have a noxfile +# run format nox session for all directories which have a noxfile for noxfile in Path(".").glob("**/noxfile.py"): - s.shell.run(["nox", "-s", "blacken"], cwd=noxfile.parent, hide_output=False) + s.shell.run(["nox", "-s", "format"], cwd=noxfile.parent, hide_output=False) diff --git a/tests/unit/gapic/functions_v2/test_function_service.py b/tests/unit/gapic/functions_v2/test_function_service.py index e98e3d9..a28e59d 100644 --- a/tests/unit/gapic/functions_v2/test_function_service.py +++ b/tests/unit/gapic/functions_v2/test_function_service.py @@ -22,32 +22,23 @@ except ImportError: import mock -import grpc -from grpc.experimental import aio import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) 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 +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.cloud.functions_v2.services.function_service import ( - FunctionServiceAsyncClient, -) -from google.cloud.functions_v2.services.function_service import FunctionServiceClient -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.services.function_service import transports -from google.cloud.functions_v2.types import functions from google.cloud.location import locations_pb2 from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import options_pb2 # type: ignore @@ -56,7 +47,18 @@ from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -import google.auth +import grpc +from grpc.experimental import aio +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest + +from google.cloud.functions_v2.services.function_service import ( + FunctionServiceAsyncClient, + FunctionServiceClient, + pagers, + transports, +) +from google.cloud.functions_v2.types import functions def client_cert_source_callback(): From 792894f42c42b2619bdba7b2bd660c65464f8da8 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 14 Jul 2022 12:43:28 +0000 Subject: [PATCH 12/16] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-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 --- noxfile.py | 1 - 1 file changed, 1 deletion(-) diff --git a/noxfile.py b/noxfile.py index 94b2f9c..001ec73 100644 --- a/noxfile.py +++ b/noxfile.py @@ -17,7 +17,6 @@ # Generated by synthtool. DO NOT EDIT! from __future__ import absolute_import - import os import pathlib import re From 492c8ce68fe67617b76f75f034cb1b8578606c66 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 14 Jul 2022 12:45:01 +0000 Subject: [PATCH 13/16] restore google/cloud/functions/__init__.py --- google/cloud/functions/__init__.py | 62 +++++++++++++----------------- 1 file changed, 27 insertions(+), 35 deletions(-) diff --git a/google/cloud/functions/__init__.py b/google/cloud/functions/__init__.py index 8300518..e17aeb3 100644 --- a/google/cloud/functions/__init__.py +++ b/google/cloud/functions/__init__.py @@ -14,70 +14,62 @@ # limitations under the License. # -from google.cloud.functions_v2.services.function_service.async_client import ( - FunctionServiceAsyncClient, +from google.cloud.functions_v1.services.cloud_functions_service.async_client import ( + CloudFunctionsServiceAsyncClient, ) -from google.cloud.functions_v2.services.function_service.client import ( - FunctionServiceClient, +from google.cloud.functions_v1.services.cloud_functions_service.client import ( + CloudFunctionsServiceClient, ) -from google.cloud.functions_v2.types.functions import ( - BuildConfig, +from google.cloud.functions_v1.types.functions import ( + CallFunctionRequest, + CallFunctionResponse, + CloudFunction, + CloudFunctionStatus, CreateFunctionRequest, DeleteFunctionRequest, - Environment, - EventFilter, EventTrigger, - Function, + FailurePolicy, GenerateDownloadUrlRequest, GenerateDownloadUrlResponse, GenerateUploadUrlRequest, GenerateUploadUrlResponse, GetFunctionRequest, + HttpsTrigger, ListFunctionsRequest, ListFunctionsResponse, - ListRuntimesRequest, - ListRuntimesResponse, - OperationMetadata, - RepoSource, SecretEnvVar, SecretVolume, - ServiceConfig, - Source, - SourceProvenance, - Stage, - StateMessage, - StorageSource, + SourceRepository, UpdateFunctionRequest, ) +from google.cloud.functions_v1.types.operations import ( + OperationMetadataV1, + OperationType, +) __all__ = ( - "FunctionServiceClient", - "FunctionServiceAsyncClient", - "BuildConfig", + "CloudFunctionsServiceClient", + "CloudFunctionsServiceAsyncClient", + "CallFunctionRequest", + "CallFunctionResponse", + "CloudFunction", "CreateFunctionRequest", "DeleteFunctionRequest", - "EventFilter", "EventTrigger", - "Function", + "FailurePolicy", "GenerateDownloadUrlRequest", "GenerateDownloadUrlResponse", "GenerateUploadUrlRequest", "GenerateUploadUrlResponse", "GetFunctionRequest", + "HttpsTrigger", "ListFunctionsRequest", "ListFunctionsResponse", - "ListRuntimesRequest", - "ListRuntimesResponse", - "OperationMetadata", - "RepoSource", "SecretEnvVar", "SecretVolume", - "ServiceConfig", - "Source", - "SourceProvenance", - "Stage", - "StateMessage", - "StorageSource", + "SourceRepository", "UpdateFunctionRequest", - "Environment", + "CloudFunctionStatus", + "OperationMetadataV1", + "OperationType", ) From 33b4702d8839f52f84f095077ac76fe4ab6fbc34 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 14 Jul 2022 12:45:21 +0000 Subject: [PATCH 14/16] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-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 --- noxfile.py | 1 + 1 file changed, 1 insertion(+) diff --git a/noxfile.py b/noxfile.py index 001ec73..94b2f9c 100644 --- a/noxfile.py +++ b/noxfile.py @@ -17,6 +17,7 @@ # Generated by synthtool. DO NOT EDIT! from __future__ import absolute_import + import os import pathlib import re From 42356b88b8dd94843edcd06656c99c5e005d7a55 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 14 Jul 2022 12:46:46 +0000 Subject: [PATCH 15/16] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-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 --- noxfile.py | 1 + 1 file changed, 1 insertion(+) diff --git a/noxfile.py b/noxfile.py index 001ec73..94b2f9c 100644 --- a/noxfile.py +++ b/noxfile.py @@ -17,6 +17,7 @@ # Generated by synthtool. DO NOT EDIT! from __future__ import absolute_import + import os import pathlib import re From d14a9205909c5c662c1289b69b8535ec10977316 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 14 Jul 2022 13:05:04 +0000 Subject: [PATCH 16/16] set coverage level to 99% --- .github/workflows/unittest.yml | 2 +- noxfile.py | 2 +- owlbot.py | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index 5531b01..f76daeb 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -54,4 +54,4 @@ jobs: - name: Report coverage results run: | coverage combine .coverage-results/.coverage* - coverage report --show-missing --fail-under=100 + coverage report --show-missing --fail-under=99 diff --git a/noxfile.py b/noxfile.py index 94b2f9c..94504ea 100644 --- a/noxfile.py +++ b/noxfile.py @@ -266,7 +266,7 @@ def cover(session): 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", "report", "--show-missing", "--fail-under=99") session.run("coverage", "erase") diff --git a/owlbot.py b/owlbot.py index 5629e2e..3185247 100644 --- a/owlbot.py +++ b/owlbot.py @@ -60,6 +60,7 @@ # ---------------------------------------------------------------------------- templated_files = gcp.CommonTemplates().py_library( + cov_level=99, microgenerator=True, versions=gcp.common.detect_versions(path="./google", default_first=True), )