From a13cf1a912dded360fa80592e93677d23200fe70 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 23 Jul 2021 21:22:43 +0000 Subject: [PATCH 1/2] fix: enable self signed jwt for grpc chore: use gapic-generator-python 0.50.5 PiperOrigin-RevId: 386504689 Source-Link: https://github.com/googleapis/googleapis/commit/762094a99ac6e03a17516b13dfbef37927267a70 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6bfc480e1a161d5de121c2bcc3745885d33b265a --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + .../v1/docs/cloudbuild_v1/cloud_build.rst | 10 + .../v1/docs/cloudbuild_v1/services.rst | 6 + .../v1/docs/cloudbuild_v1/types.rst | 7 + owl-bot-staging/v1/docs/conf.py | 376 ++ owl-bot-staging/v1/docs/index.rst | 7 + .../v1/google/devtools/cloudbuild/__init__.py | 129 + .../v1/google/devtools/cloudbuild/py.typed | 2 + .../google/devtools/cloudbuild_v1/__init__.py | 130 + .../cloudbuild_v1/gapic_metadata.json | 193 + .../v1/google/devtools/cloudbuild_v1/py.typed | 2 + .../cloudbuild_v1/services/__init__.py | 15 + .../services/cloud_build/__init__.py | 22 + .../services/cloud_build/async_client.py | 1824 ++++++ .../services/cloud_build/client.py | 2039 +++++++ .../services/cloud_build/pagers.py | 384 ++ .../cloud_build/transports/__init__.py | 33 + .../services/cloud_build/transports/base.py | 449 ++ .../services/cloud_build/transports/grpc.py | 745 +++ .../cloud_build/transports/grpc_asyncio.py | 749 +++ .../devtools/cloudbuild_v1/types/__init__.py | 126 + .../cloudbuild_v1/types/cloudbuild.py | 2693 +++++++++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + .../scripts/fixup_cloudbuild_v1_keywords.py | 192 + owl-bot-staging/v1/setup.py | 54 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/cloudbuild_v1/__init__.py | 16 + .../gapic/cloudbuild_v1/test_cloud_build.py | 5062 +++++++++++++++++ 33 files changed, 15516 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/cloudbuild_v1/cloud_build.rst create mode 100644 owl-bot-staging/v1/docs/cloudbuild_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/cloudbuild_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild/__init__.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild/py.typed create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/py.typed create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/__init__.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/async_client.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/client.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/pagers.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/base.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/cloudbuild.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/scripts/fixup_cloudbuild_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/cloudbuild_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 00000000..0bca5911 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/devtools/cloudbuild/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 00000000..7e2b155f --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/devtools/cloudbuild *.py +recursive-include google/devtools/cloudbuild_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 00000000..d4e3fd01 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Devtools Cloudbuild 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 Devtools Cloudbuild 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/cloudbuild_v1/cloud_build.rst b/owl-bot-staging/v1/docs/cloudbuild_v1/cloud_build.rst new file mode 100644 index 00000000..1e69b936 --- /dev/null +++ b/owl-bot-staging/v1/docs/cloudbuild_v1/cloud_build.rst @@ -0,0 +1,10 @@ +CloudBuild +---------------------------- + +.. automodule:: google.devtools.cloudbuild_v1.services.cloud_build + :members: + :inherited-members: + +.. automodule:: google.devtools.cloudbuild_v1.services.cloud_build.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/cloudbuild_v1/services.rst b/owl-bot-staging/v1/docs/cloudbuild_v1/services.rst new file mode 100644 index 00000000..87309bc9 --- /dev/null +++ b/owl-bot-staging/v1/docs/cloudbuild_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Devtools Cloudbuild v1 API +============================================== +.. toctree:: + :maxdepth: 2 + + cloud_build diff --git a/owl-bot-staging/v1/docs/cloudbuild_v1/types.rst b/owl-bot-staging/v1/docs/cloudbuild_v1/types.rst new file mode 100644 index 00000000..c865836d --- /dev/null +++ b/owl-bot-staging/v1/docs/cloudbuild_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Devtools Cloudbuild v1 API +=========================================== + +.. automodule:: google.devtools.cloudbuild_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 00000000..6d4458bc --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-devtools-cloudbuild documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-devtools-cloudbuild" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Devtools 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-devtools-cloudbuild-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-devtools-cloudbuild.tex", + u"google-devtools-cloudbuild Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-devtools-cloudbuild", + u"Google Devtools Cloudbuild Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-devtools-cloudbuild", + u"google-devtools-cloudbuild Documentation", + author, + "google-devtools-cloudbuild", + "GAPIC library for Google Devtools Cloudbuild API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 00000000..37eed237 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + cloudbuild_v1/services + cloudbuild_v1/types diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild/__init__.py new file mode 100644 index 00000000..832cf1fb --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild/__init__.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.devtools.cloudbuild_v1.services.cloud_build.client import CloudBuildClient +from google.devtools.cloudbuild_v1.services.cloud_build.async_client import CloudBuildAsyncClient + +from google.devtools.cloudbuild_v1.types.cloudbuild import ArtifactResult +from google.devtools.cloudbuild_v1.types.cloudbuild import Artifacts +from google.devtools.cloudbuild_v1.types.cloudbuild import Build +from google.devtools.cloudbuild_v1.types.cloudbuild import BuildOperationMetadata +from google.devtools.cloudbuild_v1.types.cloudbuild import BuildOptions +from google.devtools.cloudbuild_v1.types.cloudbuild import BuildStep +from google.devtools.cloudbuild_v1.types.cloudbuild import BuildTrigger +from google.devtools.cloudbuild_v1.types.cloudbuild import BuiltImage +from google.devtools.cloudbuild_v1.types.cloudbuild import CancelBuildRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import CreateBuildRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import CreateBuildTriggerRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import CreateWorkerPoolOperationMetadata +from google.devtools.cloudbuild_v1.types.cloudbuild import CreateWorkerPoolRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import DeleteBuildTriggerRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import DeleteWorkerPoolOperationMetadata +from google.devtools.cloudbuild_v1.types.cloudbuild import DeleteWorkerPoolRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import FileHashes +from google.devtools.cloudbuild_v1.types.cloudbuild import GetBuildRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import GetBuildTriggerRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import GetWorkerPoolRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import GitHubEventsConfig +from google.devtools.cloudbuild_v1.types.cloudbuild import Hash +from google.devtools.cloudbuild_v1.types.cloudbuild import InlineSecret +from google.devtools.cloudbuild_v1.types.cloudbuild import ListBuildsRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import ListBuildsResponse +from google.devtools.cloudbuild_v1.types.cloudbuild import ListBuildTriggersRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import ListBuildTriggersResponse +from google.devtools.cloudbuild_v1.types.cloudbuild import ListWorkerPoolsRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import ListWorkerPoolsResponse +from google.devtools.cloudbuild_v1.types.cloudbuild import PrivatePoolV1Config +from google.devtools.cloudbuild_v1.types.cloudbuild import PubsubConfig +from google.devtools.cloudbuild_v1.types.cloudbuild import PullRequestFilter +from google.devtools.cloudbuild_v1.types.cloudbuild import PushFilter +from google.devtools.cloudbuild_v1.types.cloudbuild import ReceiveTriggerWebhookRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import ReceiveTriggerWebhookResponse +from google.devtools.cloudbuild_v1.types.cloudbuild import RepoSource +from google.devtools.cloudbuild_v1.types.cloudbuild import Results +from google.devtools.cloudbuild_v1.types.cloudbuild import RetryBuildRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import RunBuildTriggerRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import Secret +from google.devtools.cloudbuild_v1.types.cloudbuild import SecretManagerSecret +from google.devtools.cloudbuild_v1.types.cloudbuild import Secrets +from google.devtools.cloudbuild_v1.types.cloudbuild import Source +from google.devtools.cloudbuild_v1.types.cloudbuild import SourceProvenance +from google.devtools.cloudbuild_v1.types.cloudbuild import StorageSource +from google.devtools.cloudbuild_v1.types.cloudbuild import StorageSourceManifest +from google.devtools.cloudbuild_v1.types.cloudbuild import TimeSpan +from google.devtools.cloudbuild_v1.types.cloudbuild import UpdateBuildTriggerRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import UpdateWorkerPoolOperationMetadata +from google.devtools.cloudbuild_v1.types.cloudbuild import UpdateWorkerPoolRequest +from google.devtools.cloudbuild_v1.types.cloudbuild import Volume +from google.devtools.cloudbuild_v1.types.cloudbuild import WebhookConfig +from google.devtools.cloudbuild_v1.types.cloudbuild import WorkerPool + +__all__ = ('CloudBuildClient', + 'CloudBuildAsyncClient', + 'ArtifactResult', + 'Artifacts', + 'Build', + 'BuildOperationMetadata', + 'BuildOptions', + 'BuildStep', + 'BuildTrigger', + 'BuiltImage', + 'CancelBuildRequest', + 'CreateBuildRequest', + 'CreateBuildTriggerRequest', + 'CreateWorkerPoolOperationMetadata', + 'CreateWorkerPoolRequest', + 'DeleteBuildTriggerRequest', + 'DeleteWorkerPoolOperationMetadata', + 'DeleteWorkerPoolRequest', + 'FileHashes', + 'GetBuildRequest', + 'GetBuildTriggerRequest', + 'GetWorkerPoolRequest', + 'GitHubEventsConfig', + 'Hash', + 'InlineSecret', + 'ListBuildsRequest', + 'ListBuildsResponse', + 'ListBuildTriggersRequest', + 'ListBuildTriggersResponse', + 'ListWorkerPoolsRequest', + 'ListWorkerPoolsResponse', + 'PrivatePoolV1Config', + 'PubsubConfig', + 'PullRequestFilter', + 'PushFilter', + 'ReceiveTriggerWebhookRequest', + 'ReceiveTriggerWebhookResponse', + 'RepoSource', + 'Results', + 'RetryBuildRequest', + 'RunBuildTriggerRequest', + 'Secret', + 'SecretManagerSecret', + 'Secrets', + 'Source', + 'SourceProvenance', + 'StorageSource', + 'StorageSourceManifest', + 'TimeSpan', + 'UpdateBuildTriggerRequest', + 'UpdateWorkerPoolOperationMetadata', + 'UpdateWorkerPoolRequest', + 'Volume', + 'WebhookConfig', + 'WorkerPool', +) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild/py.typed b/owl-bot-staging/v1/google/devtools/cloudbuild/py.typed new file mode 100644 index 00000000..076585a1 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-devtools-cloudbuild package uses inline types. diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/__init__.py new file mode 100644 index 00000000..e5293946 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/__init__.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.cloud_build import CloudBuildClient +from .services.cloud_build import CloudBuildAsyncClient + +from .types.cloudbuild import ArtifactResult +from .types.cloudbuild import Artifacts +from .types.cloudbuild import Build +from .types.cloudbuild import BuildOperationMetadata +from .types.cloudbuild import BuildOptions +from .types.cloudbuild import BuildStep +from .types.cloudbuild import BuildTrigger +from .types.cloudbuild import BuiltImage +from .types.cloudbuild import CancelBuildRequest +from .types.cloudbuild import CreateBuildRequest +from .types.cloudbuild import CreateBuildTriggerRequest +from .types.cloudbuild import CreateWorkerPoolOperationMetadata +from .types.cloudbuild import CreateWorkerPoolRequest +from .types.cloudbuild import DeleteBuildTriggerRequest +from .types.cloudbuild import DeleteWorkerPoolOperationMetadata +from .types.cloudbuild import DeleteWorkerPoolRequest +from .types.cloudbuild import FileHashes +from .types.cloudbuild import GetBuildRequest +from .types.cloudbuild import GetBuildTriggerRequest +from .types.cloudbuild import GetWorkerPoolRequest +from .types.cloudbuild import GitHubEventsConfig +from .types.cloudbuild import Hash +from .types.cloudbuild import InlineSecret +from .types.cloudbuild import ListBuildsRequest +from .types.cloudbuild import ListBuildsResponse +from .types.cloudbuild import ListBuildTriggersRequest +from .types.cloudbuild import ListBuildTriggersResponse +from .types.cloudbuild import ListWorkerPoolsRequest +from .types.cloudbuild import ListWorkerPoolsResponse +from .types.cloudbuild import PrivatePoolV1Config +from .types.cloudbuild import PubsubConfig +from .types.cloudbuild import PullRequestFilter +from .types.cloudbuild import PushFilter +from .types.cloudbuild import ReceiveTriggerWebhookRequest +from .types.cloudbuild import ReceiveTriggerWebhookResponse +from .types.cloudbuild import RepoSource +from .types.cloudbuild import Results +from .types.cloudbuild import RetryBuildRequest +from .types.cloudbuild import RunBuildTriggerRequest +from .types.cloudbuild import Secret +from .types.cloudbuild import SecretManagerSecret +from .types.cloudbuild import Secrets +from .types.cloudbuild import Source +from .types.cloudbuild import SourceProvenance +from .types.cloudbuild import StorageSource +from .types.cloudbuild import StorageSourceManifest +from .types.cloudbuild import TimeSpan +from .types.cloudbuild import UpdateBuildTriggerRequest +from .types.cloudbuild import UpdateWorkerPoolOperationMetadata +from .types.cloudbuild import UpdateWorkerPoolRequest +from .types.cloudbuild import Volume +from .types.cloudbuild import WebhookConfig +from .types.cloudbuild import WorkerPool + +__all__ = ( + 'CloudBuildAsyncClient', +'ArtifactResult', +'Artifacts', +'Build', +'BuildOperationMetadata', +'BuildOptions', +'BuildStep', +'BuildTrigger', +'BuiltImage', +'CancelBuildRequest', +'CloudBuildClient', +'CreateBuildRequest', +'CreateBuildTriggerRequest', +'CreateWorkerPoolOperationMetadata', +'CreateWorkerPoolRequest', +'DeleteBuildTriggerRequest', +'DeleteWorkerPoolOperationMetadata', +'DeleteWorkerPoolRequest', +'FileHashes', +'GetBuildRequest', +'GetBuildTriggerRequest', +'GetWorkerPoolRequest', +'GitHubEventsConfig', +'Hash', +'InlineSecret', +'ListBuildTriggersRequest', +'ListBuildTriggersResponse', +'ListBuildsRequest', +'ListBuildsResponse', +'ListWorkerPoolsRequest', +'ListWorkerPoolsResponse', +'PrivatePoolV1Config', +'PubsubConfig', +'PullRequestFilter', +'PushFilter', +'ReceiveTriggerWebhookRequest', +'ReceiveTriggerWebhookResponse', +'RepoSource', +'Results', +'RetryBuildRequest', +'RunBuildTriggerRequest', +'Secret', +'SecretManagerSecret', +'Secrets', +'Source', +'SourceProvenance', +'StorageSource', +'StorageSourceManifest', +'TimeSpan', +'UpdateBuildTriggerRequest', +'UpdateWorkerPoolOperationMetadata', +'UpdateWorkerPoolRequest', +'Volume', +'WebhookConfig', +'WorkerPool', +) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/gapic_metadata.json b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/gapic_metadata.json new file mode 100644 index 00000000..e2f307b5 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/gapic_metadata.json @@ -0,0 +1,193 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.devtools.cloudbuild_v1", + "protoPackage": "google.devtools.cloudbuild.v1", + "schema": "1.0", + "services": { + "CloudBuild": { + "clients": { + "grpc": { + "libraryClient": "CloudBuildClient", + "rpcs": { + "CancelBuild": { + "methods": [ + "cancel_build" + ] + }, + "CreateBuild": { + "methods": [ + "create_build" + ] + }, + "CreateBuildTrigger": { + "methods": [ + "create_build_trigger" + ] + }, + "CreateWorkerPool": { + "methods": [ + "create_worker_pool" + ] + }, + "DeleteBuildTrigger": { + "methods": [ + "delete_build_trigger" + ] + }, + "DeleteWorkerPool": { + "methods": [ + "delete_worker_pool" + ] + }, + "GetBuild": { + "methods": [ + "get_build" + ] + }, + "GetBuildTrigger": { + "methods": [ + "get_build_trigger" + ] + }, + "GetWorkerPool": { + "methods": [ + "get_worker_pool" + ] + }, + "ListBuildTriggers": { + "methods": [ + "list_build_triggers" + ] + }, + "ListBuilds": { + "methods": [ + "list_builds" + ] + }, + "ListWorkerPools": { + "methods": [ + "list_worker_pools" + ] + }, + "ReceiveTriggerWebhook": { + "methods": [ + "receive_trigger_webhook" + ] + }, + "RetryBuild": { + "methods": [ + "retry_build" + ] + }, + "RunBuildTrigger": { + "methods": [ + "run_build_trigger" + ] + }, + "UpdateBuildTrigger": { + "methods": [ + "update_build_trigger" + ] + }, + "UpdateWorkerPool": { + "methods": [ + "update_worker_pool" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudBuildAsyncClient", + "rpcs": { + "CancelBuild": { + "methods": [ + "cancel_build" + ] + }, + "CreateBuild": { + "methods": [ + "create_build" + ] + }, + "CreateBuildTrigger": { + "methods": [ + "create_build_trigger" + ] + }, + "CreateWorkerPool": { + "methods": [ + "create_worker_pool" + ] + }, + "DeleteBuildTrigger": { + "methods": [ + "delete_build_trigger" + ] + }, + "DeleteWorkerPool": { + "methods": [ + "delete_worker_pool" + ] + }, + "GetBuild": { + "methods": [ + "get_build" + ] + }, + "GetBuildTrigger": { + "methods": [ + "get_build_trigger" + ] + }, + "GetWorkerPool": { + "methods": [ + "get_worker_pool" + ] + }, + "ListBuildTriggers": { + "methods": [ + "list_build_triggers" + ] + }, + "ListBuilds": { + "methods": [ + "list_builds" + ] + }, + "ListWorkerPools": { + "methods": [ + "list_worker_pools" + ] + }, + "ReceiveTriggerWebhook": { + "methods": [ + "receive_trigger_webhook" + ] + }, + "RetryBuild": { + "methods": [ + "retry_build" + ] + }, + "RunBuildTrigger": { + "methods": [ + "run_build_trigger" + ] + }, + "UpdateBuildTrigger": { + "methods": [ + "update_build_trigger" + ] + }, + "UpdateWorkerPool": { + "methods": [ + "update_worker_pool" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/py.typed b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/py.typed new file mode 100644 index 00000000..076585a1 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-devtools-cloudbuild package uses inline types. diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/__init__.py new file mode 100644 index 00000000..2da912a7 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CloudBuildClient +from .async_client import CloudBuildAsyncClient + +__all__ = ( + 'CloudBuildClient', + 'CloudBuildAsyncClient', +) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/async_client.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/async_client.py new file mode 100644 index 00000000..f302ab32 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/async_client.py @@ -0,0 +1,1824 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.devtools.cloudbuild_v1.services.cloud_build import pagers +from google.devtools.cloudbuild_v1.types import cloudbuild +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CloudBuildTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CloudBuildGrpcAsyncIOTransport +from .client import CloudBuildClient + + +class CloudBuildAsyncClient: + """Creates and manages builds on Google Cloud Platform. + + The main concept used by this API is a ``Build``, which describes + the location of the source to build, how to build the source, and + where to store the built artifacts, if any. + + A user can list previously-requested builds or get builds by their + ID to determine the status of the build. + """ + + _client: CloudBuildClient + + DEFAULT_ENDPOINT = CloudBuildClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudBuildClient.DEFAULT_MTLS_ENDPOINT + + build_path = staticmethod(CloudBuildClient.build_path) + parse_build_path = staticmethod(CloudBuildClient.parse_build_path) + build_trigger_path = staticmethod(CloudBuildClient.build_trigger_path) + parse_build_trigger_path = staticmethod(CloudBuildClient.parse_build_trigger_path) + crypto_key_path = staticmethod(CloudBuildClient.crypto_key_path) + parse_crypto_key_path = staticmethod(CloudBuildClient.parse_crypto_key_path) + network_path = staticmethod(CloudBuildClient.network_path) + parse_network_path = staticmethod(CloudBuildClient.parse_network_path) + secret_version_path = staticmethod(CloudBuildClient.secret_version_path) + parse_secret_version_path = staticmethod(CloudBuildClient.parse_secret_version_path) + service_account_path = staticmethod(CloudBuildClient.service_account_path) + parse_service_account_path = staticmethod(CloudBuildClient.parse_service_account_path) + subscription_path = staticmethod(CloudBuildClient.subscription_path) + parse_subscription_path = staticmethod(CloudBuildClient.parse_subscription_path) + topic_path = staticmethod(CloudBuildClient.topic_path) + parse_topic_path = staticmethod(CloudBuildClient.parse_topic_path) + worker_pool_path = staticmethod(CloudBuildClient.worker_pool_path) + parse_worker_pool_path = staticmethod(CloudBuildClient.parse_worker_pool_path) + common_billing_account_path = staticmethod(CloudBuildClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CloudBuildClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CloudBuildClient.common_folder_path) + parse_common_folder_path = staticmethod(CloudBuildClient.parse_common_folder_path) + common_organization_path = staticmethod(CloudBuildClient.common_organization_path) + parse_common_organization_path = staticmethod(CloudBuildClient.parse_common_organization_path) + common_project_path = staticmethod(CloudBuildClient.common_project_path) + parse_common_project_path = staticmethod(CloudBuildClient.parse_common_project_path) + common_location_path = staticmethod(CloudBuildClient.common_location_path) + parse_common_location_path = staticmethod(CloudBuildClient.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: + CloudBuildAsyncClient: The constructed client. + """ + return CloudBuildClient.from_service_account_info.__func__(CloudBuildAsyncClient, 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: + CloudBuildAsyncClient: The constructed client. + """ + return CloudBuildClient.from_service_account_file.__func__(CloudBuildAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CloudBuildTransport: + """Returns the transport used by the client instance. + + Returns: + CloudBuildTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CloudBuildClient).get_transport_class, type(CloudBuildClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CloudBuildTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud build 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, ~.CloudBuildTransport]): 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 = CloudBuildClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_build(self, + request: cloudbuild.CreateBuildRequest = None, + *, + project_id: str = None, + build: cloudbuild.Build = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts a build with the specified configuration. + + This method returns a long-running ``Operation``, which includes + the build ID. Pass the build ID to ``GetBuild`` to determine the + build status (such as ``SUCCESS`` or ``FAILURE``). + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.CreateBuildRequest`): + The request object. Request to create a new build. + project_id (:class:`str`): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + build (:class:`google.devtools.cloudbuild_v1.types.Build`): + Required. Build resource to create. + This corresponds to the ``build`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.devtools.cloudbuild_v1.types.Build` A + build resource in the Cloud Build API. + + At a high level, a Build describes where to find + source code, how to build it (for example, the + builder image to run on the source), and where to + store the built artifacts. + + Fields can include the following variables, which + will be expanded when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified + by RepoSource. + - $BRANCH_NAME: the branch name specified by + RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA + specified by RepoSource or resolved from the + specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or + $COMMIT_SHA. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, build]) + if request is 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 = cloudbuild.CreateBuildRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if build is not None: + request.build = build + + # 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_build, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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, + cloudbuild.Build, + metadata_type=cloudbuild.BuildOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_build(self, + request: cloudbuild.GetBuildRequest = None, + *, + project_id: str = None, + id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.Build: + r"""Returns information about a previously requested build. + + The ``Build`` that is returned includes its status (such as + ``SUCCESS``, ``FAILURE``, or ``WORKING``), and timing + information. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.GetBuildRequest`): + The request object. Request to get a build. + project_id (:class:`str`): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + id (:class:`str`): + Required. ID of the build. + This corresponds to the ``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.devtools.cloudbuild_v1.types.Build: + A build resource in the Cloud Build API. + + At a high level, a Build describes where to find + source code, how to build it (for example, the + builder image to run on the source), and where to + store the built artifacts. + + Fields can include the following variables, which + will be expanded when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified + by RepoSource. + - $BRANCH_NAME: the branch name specified by + RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA + specified by RepoSource or resolved from the + specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or + $COMMIT_SHA. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, 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 = cloudbuild.GetBuildRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if id is not None: + request.id = 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.get_build, + 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, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_builds(self, + request: cloudbuild.ListBuildsRequest = None, + *, + project_id: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListBuildsAsyncPager: + r"""Lists previously requested builds. + Previously requested builds may still be in-progress, or + may have finished successfully or unsuccessfully. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.ListBuildsRequest`): + The request object. Request to list builds. + project_id (:class:`str`): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The raw filter text to constrain the + results. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.devtools.cloudbuild_v1.services.cloud_build.pagers.ListBuildsAsyncPager: + Response including listed builds. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, filter]) + if request is 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 = cloudbuild.ListBuildsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if filter is not None: + request.filter = filter + + # 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_builds, + 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, + ) + + # 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.ListBuildsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_build(self, + request: cloudbuild.CancelBuildRequest = None, + *, + project_id: str = None, + id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.Build: + r"""Cancels a build in progress. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.CancelBuildRequest`): + The request object. Request to cancel an ongoing build. + project_id (:class:`str`): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + id (:class:`str`): + Required. ID of the build. + This corresponds to the ``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.devtools.cloudbuild_v1.types.Build: + A build resource in the Cloud Build API. + + At a high level, a Build describes where to find + source code, how to build it (for example, the + builder image to run on the source), and where to + store the built artifacts. + + Fields can include the following variables, which + will be expanded when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified + by RepoSource. + - $BRANCH_NAME: the branch name specified by + RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA + specified by RepoSource or resolved from the + specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or + $COMMIT_SHA. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, 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 = cloudbuild.CancelBuildRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if id is not None: + request.id = 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.cancel_build, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def retry_build(self, + request: cloudbuild.RetryBuildRequest = None, + *, + project_id: str = None, + id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new build based on the specified build. + + This method creates a new build using the original build + request, which may or may not result in an identical build. + + For triggered builds: + + - Triggered builds resolve to a precise revision; therefore a + retry of a triggered build will result in a build that uses + the same revision. + + For non-triggered builds that specify ``RepoSource``: + + - If the original build built from the tip of a branch, the + retried build will build from the tip of that branch, which + may not be the same revision as the original build. + - If the original build specified a commit sha or revision ID, + the retried build will use the identical source. + + For builds that specify ``StorageSource``: + + - If the original build pulled source from Google Cloud Storage + without specifying the generation of the object, the new + build will use the current object, which may be different + from the original build source. + - If the original build pulled source from Cloud Storage and + specified the generation of the object, the new build will + attempt to use the same object, which may or may not be + available depending on the bucket's lifecycle management + settings. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.RetryBuildRequest`): + The request object. Specifies a build to retry. + project_id (:class:`str`): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + id (:class:`str`): + Required. Build ID of the original + build. + + This corresponds to the ``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.devtools.cloudbuild_v1.types.Build` A + build resource in the Cloud Build API. + + At a high level, a Build describes where to find + source code, how to build it (for example, the + builder image to run on the source), and where to + store the built artifacts. + + Fields can include the following variables, which + will be expanded when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified + by RepoSource. + - $BRANCH_NAME: the branch name specified by + RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA + specified by RepoSource or resolved from the + specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or + $COMMIT_SHA. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, 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 = cloudbuild.RetryBuildRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if id is not None: + request.id = 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.retry_build, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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, + cloudbuild.Build, + metadata_type=cloudbuild.BuildOperationMetadata, + ) + + # Done; return the response. + return response + + async def create_build_trigger(self, + request: cloudbuild.CreateBuildTriggerRequest = None, + *, + project_id: str = None, + trigger: cloudbuild.BuildTrigger = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.BuildTrigger: + r"""Creates a new ``BuildTrigger``. + + This API is experimental. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.CreateBuildTriggerRequest`): + The request object. Request to create a new + `BuildTrigger`. + project_id (:class:`str`): + Required. ID of the project for which + to configure automatic builds. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger (:class:`google.devtools.cloudbuild_v1.types.BuildTrigger`): + Required. ``BuildTrigger`` to create. + This corresponds to the ``trigger`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.devtools.cloudbuild_v1.types.BuildTrigger: + Configuration for an automated build + in response to source repository + changes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trigger]) + if request is 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 = cloudbuild.CreateBuildTriggerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trigger is not None: + request.trigger = trigger + + # 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_build_trigger, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_build_trigger(self, + request: cloudbuild.GetBuildTriggerRequest = None, + *, + project_id: str = None, + trigger_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.BuildTrigger: + r"""Returns information about a ``BuildTrigger``. + + This API is experimental. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.GetBuildTriggerRequest`): + The request object. Returns the `BuildTrigger` with the + specified ID. + project_id (:class:`str`): + Required. ID of the project that owns + the trigger. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger_id (:class:`str`): + Required. Identifier (``id`` or ``name``) of the + ``BuildTrigger`` to get. + + This corresponds to the ``trigger_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.devtools.cloudbuild_v1.types.BuildTrigger: + Configuration for an automated build + in response to source repository + changes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trigger_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 = cloudbuild.GetBuildTriggerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trigger_id is not None: + request.trigger_id = trigger_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.get_build_trigger, + 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, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_build_triggers(self, + request: cloudbuild.ListBuildTriggersRequest = None, + *, + project_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListBuildTriggersAsyncPager: + r"""Lists existing ``BuildTrigger``\ s. + + This API is experimental. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.ListBuildTriggersRequest`): + The request object. Request to list existing + `BuildTriggers`. + project_id (:class:`str`): + Required. ID of the project for which + to list BuildTriggers. + + This corresponds to the ``project_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.devtools.cloudbuild_v1.services.cloud_build.pagers.ListBuildTriggersAsyncPager: + Response containing existing BuildTriggers. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_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 = cloudbuild.ListBuildTriggersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_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.list_build_triggers, + 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, + ) + + # 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.ListBuildTriggersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_build_trigger(self, + request: cloudbuild.DeleteBuildTriggerRequest = None, + *, + project_id: str = None, + trigger_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ``BuildTrigger`` by its project ID and trigger ID. + + This API is experimental. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.DeleteBuildTriggerRequest`): + The request object. Request to delete a `BuildTrigger`. + project_id (:class:`str`): + Required. ID of the project that owns + the trigger. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger_id (:class:`str`): + Required. ID of the ``BuildTrigger`` to delete. + This corresponds to the ``trigger_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. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trigger_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 = cloudbuild.DeleteBuildTriggerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trigger_id is not None: + request.trigger_id = trigger_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.delete_build_trigger, + 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, + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_build_trigger(self, + request: cloudbuild.UpdateBuildTriggerRequest = None, + *, + project_id: str = None, + trigger_id: str = None, + trigger: cloudbuild.BuildTrigger = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.BuildTrigger: + r"""Updates a ``BuildTrigger`` by its project ID and trigger ID. + + This API is experimental. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.UpdateBuildTriggerRequest`): + The request object. Request to update an existing + `BuildTrigger`. + project_id (:class:`str`): + Required. ID of the project that owns + the trigger. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger_id (:class:`str`): + Required. ID of the ``BuildTrigger`` to update. + This corresponds to the ``trigger_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger (:class:`google.devtools.cloudbuild_v1.types.BuildTrigger`): + Required. ``BuildTrigger`` to update. + This corresponds to the ``trigger`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.devtools.cloudbuild_v1.types.BuildTrigger: + Configuration for an automated build + in response to source repository + changes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trigger_id, trigger]) + if request is 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 = cloudbuild.UpdateBuildTriggerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trigger_id is not None: + request.trigger_id = trigger_id + if trigger is not None: + request.trigger = trigger + + # 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_build_trigger, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_build_trigger(self, + request: cloudbuild.RunBuildTriggerRequest = None, + *, + project_id: str = None, + trigger_id: str = None, + source: cloudbuild.RepoSource = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs a ``BuildTrigger`` at a particular source revision. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.RunBuildTriggerRequest`): + The request object. Specifies a build trigger to run and + the source to use. + project_id (:class:`str`): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger_id (:class:`str`): + Required. ID of the trigger. + This corresponds to the ``trigger_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.devtools.cloudbuild_v1.types.RepoSource`): + Source to build against this trigger. + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.devtools.cloudbuild_v1.types.Build` A + build resource in the Cloud Build API. + + At a high level, a Build describes where to find + source code, how to build it (for example, the + builder image to run on the source), and where to + store the built artifacts. + + Fields can include the following variables, which + will be expanded when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified + by RepoSource. + - $BRANCH_NAME: the branch name specified by + RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA + specified by RepoSource or resolved from the + specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or + $COMMIT_SHA. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trigger_id, source]) + if request is 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 = cloudbuild.RunBuildTriggerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trigger_id is not None: + request.trigger_id = trigger_id + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_build_trigger, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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, + cloudbuild.Build, + metadata_type=cloudbuild.BuildOperationMetadata, + ) + + # Done; return the response. + return response + + async def receive_trigger_webhook(self, + request: cloudbuild.ReceiveTriggerWebhookRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.ReceiveTriggerWebhookResponse: + r"""ReceiveTriggerWebhook [Experimental] is called when the API + receives a webhook request targeted at a specific trigger. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.ReceiveTriggerWebhookRequest`): + The request object. ReceiveTriggerWebhookRequest + [Experimental] is the request object accepted by the + ReceiveTriggerWebhook 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.devtools.cloudbuild_v1.types.ReceiveTriggerWebhookResponse: + ReceiveTriggerWebhookResponse [Experimental] is the response object for the + ReceiveTriggerWebhook method. + + """ + # Create or coerce a protobuf request object. + request = cloudbuild.ReceiveTriggerWebhookRequest(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.receive_trigger_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_worker_pool(self, + request: cloudbuild.CreateWorkerPoolRequest = None, + *, + parent: str = None, + worker_pool: cloudbuild.WorkerPool = None, + worker_pool_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a ``WorkerPool``. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.CreateWorkerPoolRequest`): + The request object. Request to create a new + `WorkerPool`. + parent (:class:`str`): + Required. The parent resource where this worker pool + will be created. Format: + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + worker_pool (:class:`google.devtools.cloudbuild_v1.types.WorkerPool`): + Required. ``WorkerPool`` resource to create. + This corresponds to the ``worker_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + worker_pool_id (:class:`str`): + Required. Immutable. The ID to use for the + ``WorkerPool``, which will become the final component of + the resource name. + + This value should be 1-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``worker_pool_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.devtools.cloudbuild_v1.types.WorkerPool` + Configuration for a WorkerPool. + + Cloud Build owns and maintains a pool of workers for + general use and have no access to a project's private + network. By default, builds submitted to Cloud Build + will use a worker from this pool. + + If your build needs access to resources on a private + network, create and use a WorkerPool to run your + builds. Private WorkerPools give your builds access + to any single VPC network that you administer, + including any on-prem resources connected to that VPC + network. For an overview of private pools, see + [Private pools + overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, worker_pool, worker_pool_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = cloudbuild.CreateWorkerPoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if worker_pool is not None: + request.worker_pool = worker_pool + if worker_pool_id is not None: + request.worker_pool_id = worker_pool_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_worker_pool, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + cloudbuild.WorkerPool, + metadata_type=cloudbuild.CreateWorkerPoolOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_worker_pool(self, + request: cloudbuild.GetWorkerPoolRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.WorkerPool: + r"""Returns details of a ``WorkerPool``. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.GetWorkerPoolRequest`): + The request object. Request to get a `WorkerPool` with + the specified name. + name (:class:`str`): + Required. The name of the ``WorkerPool`` to retrieve. + Format: + ``projects/{project}/locations/{location}/workerPools/{workerPool}``. + + 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.devtools.cloudbuild_v1.types.WorkerPool: + Configuration for a WorkerPool. + + Cloud Build owns and maintains a pool of workers for + general use and have no access to a project's private + network. By default, builds submitted to Cloud Build + will use a worker from this pool. + + If your build needs access to resources on a private + network, create and use a WorkerPool to run your + builds. Private WorkerPools give your builds access + to any single VPC network that you administer, + including any on-prem resources connected to that VPC + network. For an overview of private pools, see + [Private pools + overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = cloudbuild.GetWorkerPoolRequest(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_worker_pool, + 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 delete_worker_pool(self, + request: cloudbuild.DeleteWorkerPoolRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a ``WorkerPool``. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.DeleteWorkerPoolRequest`): + The request object. Request to delete a `WorkerPool`. + name (:class:`str`): + Required. The name of the ``WorkerPool`` to delete. + Format: + ``projects/{project}/locations/{workerPool}/workerPools/{workerPool}``. + + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = cloudbuild.DeleteWorkerPoolRequest(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_worker_pool, + 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=cloudbuild.DeleteWorkerPoolOperationMetadata, + ) + + # Done; return the response. + return response + + async def update_worker_pool(self, + request: cloudbuild.UpdateWorkerPoolRequest = None, + *, + worker_pool: cloudbuild.WorkerPool = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a ``WorkerPool``. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.UpdateWorkerPoolRequest`): + The request object. Request to update a `WorkerPool`. + worker_pool (:class:`google.devtools.cloudbuild_v1.types.WorkerPool`): + Required. The ``WorkerPool`` to update. + + The ``name`` field is used to identify the + ``WorkerPool`` to update. Format: + ``projects/{project}/locations/{location}/workerPools/{workerPool}``. + + This corresponds to the ``worker_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + A mask specifying which fields in ``worker_pool`` to + update. + + 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.devtools.cloudbuild_v1.types.WorkerPool` + Configuration for a WorkerPool. + + Cloud Build owns and maintains a pool of workers for + general use and have no access to a project's private + network. By default, builds submitted to Cloud Build + will use a worker from this pool. + + If your build needs access to resources on a private + network, create and use a WorkerPool to run your + builds. Private WorkerPools give your builds access + to any single VPC network that you administer, + including any on-prem resources connected to that VPC + network. For an overview of private pools, see + [Private pools + overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([worker_pool, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = cloudbuild.UpdateWorkerPoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if worker_pool is not None: + request.worker_pool = worker_pool + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_worker_pool, + 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(( + ("worker_pool.name", request.worker_pool.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, + cloudbuild.WorkerPool, + metadata_type=cloudbuild.UpdateWorkerPoolOperationMetadata, + ) + + # Done; return the response. + return response + + async def list_worker_pools(self, + request: cloudbuild.ListWorkerPoolsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkerPoolsAsyncPager: + r"""Lists ``WorkerPool``\ s. + + Args: + request (:class:`google.devtools.cloudbuild_v1.types.ListWorkerPoolsRequest`): + The request object. Request to list `WorkerPool`s. + parent (:class:`str`): + Required. The parent of the collection of + ``WorkerPools``. Format: + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.devtools.cloudbuild_v1.services.cloud_build.pagers.ListWorkerPoolsAsyncPager: + Response containing existing WorkerPools. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = cloudbuild.ListWorkerPoolsRequest(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_worker_pools, + 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.ListWorkerPoolsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-devtools-cloudbuild", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CloudBuildAsyncClient", +) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/client.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/client.py new file mode 100644 index 00000000..841080f7 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/client.py @@ -0,0 +1,2039 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.devtools.cloudbuild_v1.services.cloud_build import pagers +from google.devtools.cloudbuild_v1.types import cloudbuild +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import CloudBuildTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CloudBuildGrpcTransport +from .transports.grpc_asyncio import CloudBuildGrpcAsyncIOTransport + + +class CloudBuildClientMeta(type): + """Metaclass for the CloudBuild 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[CloudBuildTransport]] + _transport_registry["grpc"] = CloudBuildGrpcTransport + _transport_registry["grpc_asyncio"] = CloudBuildGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CloudBuildTransport]: + """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 CloudBuildClient(metaclass=CloudBuildClientMeta): + """Creates and manages builds on Google Cloud Platform. + + The main concept used by this API is a ``Build``, which describes + the location of the source to build, how to build the source, and + where to store the built artifacts, if any. + + A user can list previously-requested builds or get builds by their + ID to determine the status of the build. + """ + + @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 = "cloudbuild.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: + CloudBuildClient: 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: + CloudBuildClient: 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) -> CloudBuildTransport: + """Returns the transport used by the client instance. + + Returns: + CloudBuildTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def build_path(project: str,build: str,) -> str: + """Returns a fully-qualified build string.""" + return "projects/{project}/builds/{build}".format(project=project, 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.+?)/builds/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def build_trigger_path(project: str,trigger: str,) -> str: + """Returns a fully-qualified build_trigger string.""" + return "projects/{project}/triggers/{trigger}".format(project=project, trigger=trigger, ) + + @staticmethod + def parse_build_trigger_path(path: str) -> Dict[str,str]: + """Parses a build_trigger path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/triggers/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_path(project: str,location: str,keyring: str,key: str,) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}".format(project=project, location=location, keyring=keyring, key=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 network_path(project: str,network: str,) -> str: + """Returns a fully-qualified network string.""" + return "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str,str]: + """Parses a network path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/global/networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def secret_version_path(project: str,secret: str,version: str,) -> str: + """Returns a fully-qualified secret_version string.""" + return "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) + + @staticmethod + def parse_secret_version_path(path: str) -> Dict[str,str]: + """Parses a secret_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_account_path(project: str,service_account: str,) -> str: + """Returns a fully-qualified service_account string.""" + return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + + @staticmethod + def parse_service_account_path(path: str) -> Dict[str,str]: + """Parses a service_account path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def subscription_path(project: str,subscription: str,) -> str: + """Returns a fully-qualified subscription string.""" + return "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) + + @staticmethod + def parse_subscription_path(path: str) -> Dict[str,str]: + """Parses a subscription path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/subscriptions/(?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 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CloudBuildTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud build 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, CloudBuildTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CloudBuildTransport): + # transport is a CloudBuildTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def create_build(self, + request: cloudbuild.CreateBuildRequest = None, + *, + project_id: str = None, + build: cloudbuild.Build = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a build with the specified configuration. + + This method returns a long-running ``Operation``, which includes + the build ID. Pass the build ID to ``GetBuild`` to determine the + build status (such as ``SUCCESS`` or ``FAILURE``). + + Args: + request (google.devtools.cloudbuild_v1.types.CreateBuildRequest): + The request object. Request to create a new build. + project_id (str): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + build (google.devtools.cloudbuild_v1.types.Build): + Required. Build resource to create. + This corresponds to the ``build`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.devtools.cloudbuild_v1.types.Build` A + build resource in the Cloud Build API. + + At a high level, a Build describes where to find + source code, how to build it (for example, the + builder image to run on the source), and where to + store the built artifacts. + + Fields can include the following variables, which + will be expanded when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified + by RepoSource. + - $BRANCH_NAME: the branch name specified by + RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA + specified by RepoSource or resolved from the + specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or + $COMMIT_SHA. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, build]) + if request is 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 cloudbuild.CreateBuildRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.CreateBuildRequest): + request = cloudbuild.CreateBuildRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if build is not None: + request.build = build + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_build] + + # 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, + cloudbuild.Build, + metadata_type=cloudbuild.BuildOperationMetadata, + ) + + # Done; return the response. + return response + + def get_build(self, + request: cloudbuild.GetBuildRequest = None, + *, + project_id: str = None, + id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.Build: + r"""Returns information about a previously requested build. + + The ``Build`` that is returned includes its status (such as + ``SUCCESS``, ``FAILURE``, or ``WORKING``), and timing + information. + + Args: + request (google.devtools.cloudbuild_v1.types.GetBuildRequest): + The request object. Request to get a build. + project_id (str): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + id (str): + Required. ID of the build. + This corresponds to the ``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.devtools.cloudbuild_v1.types.Build: + A build resource in the Cloud Build API. + + At a high level, a Build describes where to find + source code, how to build it (for example, the + builder image to run on the source), and where to + store the built artifacts. + + Fields can include the following variables, which + will be expanded when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified + by RepoSource. + - $BRANCH_NAME: the branch name specified by + RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA + specified by RepoSource or resolved from the + specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or + $COMMIT_SHA. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, 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 cloudbuild.GetBuildRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.GetBuildRequest): + request = cloudbuild.GetBuildRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if id is not None: + request.id = id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_build] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_builds(self, + request: cloudbuild.ListBuildsRequest = None, + *, + project_id: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListBuildsPager: + r"""Lists previously requested builds. + Previously requested builds may still be in-progress, or + may have finished successfully or unsuccessfully. + + Args: + request (google.devtools.cloudbuild_v1.types.ListBuildsRequest): + The request object. Request to list builds. + project_id (str): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The raw filter text to constrain the + results. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.devtools.cloudbuild_v1.services.cloud_build.pagers.ListBuildsPager: + Response including listed builds. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, filter]) + if request is 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 cloudbuild.ListBuildsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.ListBuildsRequest): + request = cloudbuild.ListBuildsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_builds] + + # 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.ListBuildsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def cancel_build(self, + request: cloudbuild.CancelBuildRequest = None, + *, + project_id: str = None, + id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.Build: + r"""Cancels a build in progress. + + Args: + request (google.devtools.cloudbuild_v1.types.CancelBuildRequest): + The request object. Request to cancel an ongoing build. + project_id (str): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + id (str): + Required. ID of the build. + This corresponds to the ``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.devtools.cloudbuild_v1.types.Build: + A build resource in the Cloud Build API. + + At a high level, a Build describes where to find + source code, how to build it (for example, the + builder image to run on the source), and where to + store the built artifacts. + + Fields can include the following variables, which + will be expanded when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified + by RepoSource. + - $BRANCH_NAME: the branch name specified by + RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA + specified by RepoSource or resolved from the + specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or + $COMMIT_SHA. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, 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 cloudbuild.CancelBuildRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.CancelBuildRequest): + request = cloudbuild.CancelBuildRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if id is not None: + request.id = id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_build] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def retry_build(self, + request: cloudbuild.RetryBuildRequest = None, + *, + project_id: str = None, + id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new build based on the specified build. + + This method creates a new build using the original build + request, which may or may not result in an identical build. + + For triggered builds: + + - Triggered builds resolve to a precise revision; therefore a + retry of a triggered build will result in a build that uses + the same revision. + + For non-triggered builds that specify ``RepoSource``: + + - If the original build built from the tip of a branch, the + retried build will build from the tip of that branch, which + may not be the same revision as the original build. + - If the original build specified a commit sha or revision ID, + the retried build will use the identical source. + + For builds that specify ``StorageSource``: + + - If the original build pulled source from Google Cloud Storage + without specifying the generation of the object, the new + build will use the current object, which may be different + from the original build source. + - If the original build pulled source from Cloud Storage and + specified the generation of the object, the new build will + attempt to use the same object, which may or may not be + available depending on the bucket's lifecycle management + settings. + + Args: + request (google.devtools.cloudbuild_v1.types.RetryBuildRequest): + The request object. Specifies a build to retry. + project_id (str): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + id (str): + Required. Build ID of the original + build. + + This corresponds to the ``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.devtools.cloudbuild_v1.types.Build` A + build resource in the Cloud Build API. + + At a high level, a Build describes where to find + source code, how to build it (for example, the + builder image to run on the source), and where to + store the built artifacts. + + Fields can include the following variables, which + will be expanded when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified + by RepoSource. + - $BRANCH_NAME: the branch name specified by + RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA + specified by RepoSource or resolved from the + specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or + $COMMIT_SHA. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, 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 cloudbuild.RetryBuildRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.RetryBuildRequest): + request = cloudbuild.RetryBuildRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if id is not None: + request.id = id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.retry_build] + + # 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, + cloudbuild.Build, + metadata_type=cloudbuild.BuildOperationMetadata, + ) + + # Done; return the response. + return response + + def create_build_trigger(self, + request: cloudbuild.CreateBuildTriggerRequest = None, + *, + project_id: str = None, + trigger: cloudbuild.BuildTrigger = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.BuildTrigger: + r"""Creates a new ``BuildTrigger``. + + This API is experimental. + + Args: + request (google.devtools.cloudbuild_v1.types.CreateBuildTriggerRequest): + The request object. Request to create a new + `BuildTrigger`. + project_id (str): + Required. ID of the project for which + to configure automatic builds. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger (google.devtools.cloudbuild_v1.types.BuildTrigger): + Required. ``BuildTrigger`` to create. + This corresponds to the ``trigger`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.devtools.cloudbuild_v1.types.BuildTrigger: + Configuration for an automated build + in response to source repository + changes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trigger]) + if request is 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 cloudbuild.CreateBuildTriggerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.CreateBuildTriggerRequest): + request = cloudbuild.CreateBuildTriggerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trigger is not None: + request.trigger = trigger + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_build_trigger] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_build_trigger(self, + request: cloudbuild.GetBuildTriggerRequest = None, + *, + project_id: str = None, + trigger_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.BuildTrigger: + r"""Returns information about a ``BuildTrigger``. + + This API is experimental. + + Args: + request (google.devtools.cloudbuild_v1.types.GetBuildTriggerRequest): + The request object. Returns the `BuildTrigger` with the + specified ID. + project_id (str): + Required. ID of the project that owns + the trigger. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger_id (str): + Required. Identifier (``id`` or ``name``) of the + ``BuildTrigger`` to get. + + This corresponds to the ``trigger_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.devtools.cloudbuild_v1.types.BuildTrigger: + Configuration for an automated build + in response to source repository + changes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trigger_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 cloudbuild.GetBuildTriggerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.GetBuildTriggerRequest): + request = cloudbuild.GetBuildTriggerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trigger_id is not None: + request.trigger_id = trigger_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_build_trigger] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_build_triggers(self, + request: cloudbuild.ListBuildTriggersRequest = None, + *, + project_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListBuildTriggersPager: + r"""Lists existing ``BuildTrigger``\ s. + + This API is experimental. + + Args: + request (google.devtools.cloudbuild_v1.types.ListBuildTriggersRequest): + The request object. Request to list existing + `BuildTriggers`. + project_id (str): + Required. ID of the project for which + to list BuildTriggers. + + This corresponds to the ``project_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.devtools.cloudbuild_v1.services.cloud_build.pagers.ListBuildTriggersPager: + Response containing existing BuildTriggers. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_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 cloudbuild.ListBuildTriggersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.ListBuildTriggersRequest): + request = cloudbuild.ListBuildTriggersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_build_triggers] + + # 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.ListBuildTriggersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_build_trigger(self, + request: cloudbuild.DeleteBuildTriggerRequest = None, + *, + project_id: str = None, + trigger_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a ``BuildTrigger`` by its project ID and trigger ID. + + This API is experimental. + + Args: + request (google.devtools.cloudbuild_v1.types.DeleteBuildTriggerRequest): + The request object. Request to delete a `BuildTrigger`. + project_id (str): + Required. ID of the project that owns + the trigger. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger_id (str): + Required. ID of the ``BuildTrigger`` to delete. + This corresponds to the ``trigger_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. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trigger_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 cloudbuild.DeleteBuildTriggerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.DeleteBuildTriggerRequest): + request = cloudbuild.DeleteBuildTriggerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trigger_id is not None: + request.trigger_id = trigger_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_build_trigger] + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_build_trigger(self, + request: cloudbuild.UpdateBuildTriggerRequest = None, + *, + project_id: str = None, + trigger_id: str = None, + trigger: cloudbuild.BuildTrigger = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.BuildTrigger: + r"""Updates a ``BuildTrigger`` by its project ID and trigger ID. + + This API is experimental. + + Args: + request (google.devtools.cloudbuild_v1.types.UpdateBuildTriggerRequest): + The request object. Request to update an existing + `BuildTrigger`. + project_id (str): + Required. ID of the project that owns + the trigger. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger_id (str): + Required. ID of the ``BuildTrigger`` to update. + This corresponds to the ``trigger_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger (google.devtools.cloudbuild_v1.types.BuildTrigger): + Required. ``BuildTrigger`` to update. + This corresponds to the ``trigger`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.devtools.cloudbuild_v1.types.BuildTrigger: + Configuration for an automated build + in response to source repository + changes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trigger_id, trigger]) + if request is 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 cloudbuild.UpdateBuildTriggerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.UpdateBuildTriggerRequest): + request = cloudbuild.UpdateBuildTriggerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trigger_id is not None: + request.trigger_id = trigger_id + if trigger is not None: + request.trigger = trigger + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_build_trigger] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_build_trigger(self, + request: cloudbuild.RunBuildTriggerRequest = None, + *, + project_id: str = None, + trigger_id: str = None, + source: cloudbuild.RepoSource = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Runs a ``BuildTrigger`` at a particular source revision. + + Args: + request (google.devtools.cloudbuild_v1.types.RunBuildTriggerRequest): + The request object. Specifies a build trigger to run and + the source to use. + project_id (str): + Required. ID of the project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger_id (str): + Required. ID of the trigger. + This corresponds to the ``trigger_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.devtools.cloudbuild_v1.types.RepoSource): + Source to build against this trigger. + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.devtools.cloudbuild_v1.types.Build` A + build resource in the Cloud Build API. + + At a high level, a Build describes where to find + source code, how to build it (for example, the + builder image to run on the source), and where to + store the built artifacts. + + Fields can include the following variables, which + will be expanded when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified + by RepoSource. + - $BRANCH_NAME: the branch name specified by + RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA + specified by RepoSource or resolved from the + specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or + $COMMIT_SHA. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trigger_id, source]) + if request is 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 cloudbuild.RunBuildTriggerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.RunBuildTriggerRequest): + request = cloudbuild.RunBuildTriggerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trigger_id is not None: + request.trigger_id = trigger_id + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_build_trigger] + + # 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, + cloudbuild.Build, + metadata_type=cloudbuild.BuildOperationMetadata, + ) + + # Done; return the response. + return response + + def receive_trigger_webhook(self, + request: cloudbuild.ReceiveTriggerWebhookRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.ReceiveTriggerWebhookResponse: + r"""ReceiveTriggerWebhook [Experimental] is called when the API + receives a webhook request targeted at a specific trigger. + + Args: + request (google.devtools.cloudbuild_v1.types.ReceiveTriggerWebhookRequest): + The request object. ReceiveTriggerWebhookRequest + [Experimental] is the request object accepted by the + ReceiveTriggerWebhook 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.devtools.cloudbuild_v1.types.ReceiveTriggerWebhookResponse: + ReceiveTriggerWebhookResponse [Experimental] is the response object for the + ReceiveTriggerWebhook method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a cloudbuild.ReceiveTriggerWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.ReceiveTriggerWebhookRequest): + request = cloudbuild.ReceiveTriggerWebhookRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.receive_trigger_webhook] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_worker_pool(self, + request: cloudbuild.CreateWorkerPoolRequest = None, + *, + parent: str = None, + worker_pool: cloudbuild.WorkerPool = None, + worker_pool_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a ``WorkerPool``. + + Args: + request (google.devtools.cloudbuild_v1.types.CreateWorkerPoolRequest): + The request object. Request to create a new + `WorkerPool`. + parent (str): + Required. The parent resource where this worker pool + will be created. Format: + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + worker_pool (google.devtools.cloudbuild_v1.types.WorkerPool): + Required. ``WorkerPool`` resource to create. + This corresponds to the ``worker_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + worker_pool_id (str): + Required. Immutable. The ID to use for the + ``WorkerPool``, which will become the final component of + the resource name. + + This value should be 1-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``worker_pool_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.devtools.cloudbuild_v1.types.WorkerPool` + Configuration for a WorkerPool. + + Cloud Build owns and maintains a pool of workers for + general use and have no access to a project's private + network. By default, builds submitted to Cloud Build + will use a worker from this pool. + + If your build needs access to resources on a private + network, create and use a WorkerPool to run your + builds. Private WorkerPools give your builds access + to any single VPC network that you administer, + including any on-prem resources connected to that VPC + network. For an overview of private pools, see + [Private pools + overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, worker_pool, worker_pool_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a cloudbuild.CreateWorkerPoolRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.CreateWorkerPoolRequest): + request = cloudbuild.CreateWorkerPoolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if worker_pool is not None: + request.worker_pool = worker_pool + if worker_pool_id is not None: + request.worker_pool_id = worker_pool_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_worker_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # 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, + cloudbuild.WorkerPool, + metadata_type=cloudbuild.CreateWorkerPoolOperationMetadata, + ) + + # Done; return the response. + return response + + def get_worker_pool(self, + request: cloudbuild.GetWorkerPoolRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloudbuild.WorkerPool: + r"""Returns details of a ``WorkerPool``. + + Args: + request (google.devtools.cloudbuild_v1.types.GetWorkerPoolRequest): + The request object. Request to get a `WorkerPool` with + the specified name. + name (str): + Required. The name of the ``WorkerPool`` to retrieve. + Format: + ``projects/{project}/locations/{location}/workerPools/{workerPool}``. + + 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.devtools.cloudbuild_v1.types.WorkerPool: + Configuration for a WorkerPool. + + Cloud Build owns and maintains a pool of workers for + general use and have no access to a project's private + network. By default, builds submitted to Cloud Build + will use a worker from this pool. + + If your build needs access to resources on a private + network, create and use a WorkerPool to run your + builds. Private WorkerPools give your builds access + to any single VPC network that you administer, + including any on-prem resources connected to that VPC + network. For an overview of private pools, see + [Private pools + overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a cloudbuild.GetWorkerPoolRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.GetWorkerPoolRequest): + request = cloudbuild.GetWorkerPoolRequest(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_worker_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_worker_pool(self, + request: cloudbuild.DeleteWorkerPoolRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a ``WorkerPool``. + + Args: + request (google.devtools.cloudbuild_v1.types.DeleteWorkerPoolRequest): + The request object. Request to delete a `WorkerPool`. + name (str): + Required. The name of the ``WorkerPool`` to delete. + Format: + ``projects/{project}/locations/{workerPool}/workerPools/{workerPool}``. + + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a cloudbuild.DeleteWorkerPoolRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.DeleteWorkerPoolRequest): + request = cloudbuild.DeleteWorkerPoolRequest(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_worker_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # 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=cloudbuild.DeleteWorkerPoolOperationMetadata, + ) + + # Done; return the response. + return response + + def update_worker_pool(self, + request: cloudbuild.UpdateWorkerPoolRequest = None, + *, + worker_pool: cloudbuild.WorkerPool = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates a ``WorkerPool``. + + Args: + request (google.devtools.cloudbuild_v1.types.UpdateWorkerPoolRequest): + The request object. Request to update a `WorkerPool`. + worker_pool (google.devtools.cloudbuild_v1.types.WorkerPool): + Required. The ``WorkerPool`` to update. + + The ``name`` field is used to identify the + ``WorkerPool`` to update. Format: + ``projects/{project}/locations/{location}/workerPools/{workerPool}``. + + This corresponds to the ``worker_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + A mask specifying which fields in ``worker_pool`` to + update. + + 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.devtools.cloudbuild_v1.types.WorkerPool` + Configuration for a WorkerPool. + + Cloud Build owns and maintains a pool of workers for + general use and have no access to a project's private + network. By default, builds submitted to Cloud Build + will use a worker from this pool. + + If your build needs access to resources on a private + network, create and use a WorkerPool to run your + builds. Private WorkerPools give your builds access + to any single VPC network that you administer, + including any on-prem resources connected to that VPC + network. For an overview of private pools, see + [Private pools + overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([worker_pool, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a cloudbuild.UpdateWorkerPoolRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.UpdateWorkerPoolRequest): + request = cloudbuild.UpdateWorkerPoolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if worker_pool is not None: + request.worker_pool = worker_pool + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_worker_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("worker_pool.name", request.worker_pool.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, + cloudbuild.WorkerPool, + metadata_type=cloudbuild.UpdateWorkerPoolOperationMetadata, + ) + + # Done; return the response. + return response + + def list_worker_pools(self, + request: cloudbuild.ListWorkerPoolsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkerPoolsPager: + r"""Lists ``WorkerPool``\ s. + + Args: + request (google.devtools.cloudbuild_v1.types.ListWorkerPoolsRequest): + The request object. Request to list `WorkerPool`s. + parent (str): + Required. The parent of the collection of + ``WorkerPools``. Format: + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.devtools.cloudbuild_v1.services.cloud_build.pagers.ListWorkerPoolsPager: + Response containing existing WorkerPools. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a cloudbuild.ListWorkerPoolsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudbuild.ListWorkerPoolsRequest): + request = cloudbuild.ListWorkerPoolsRequest(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_worker_pools] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # 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.ListWorkerPoolsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-devtools-cloudbuild", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CloudBuildClient", +) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/pagers.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/pagers.py new file mode 100644 index 00000000..c3ed5314 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/pagers.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.devtools.cloudbuild_v1.types import cloudbuild + + +class ListBuildsPager: + """A pager for iterating through ``list_builds`` requests. + + This class thinly wraps an initial + :class:`google.devtools.cloudbuild_v1.types.ListBuildsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``builds`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBuilds`` requests and continue to iterate + through the ``builds`` field on the + corresponding responses. + + All the usual :class:`google.devtools.cloudbuild_v1.types.ListBuildsResponse` + 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[..., cloudbuild.ListBuildsResponse], + request: cloudbuild.ListBuildsRequest, + response: cloudbuild.ListBuildsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.devtools.cloudbuild_v1.types.ListBuildsRequest): + The initial request object. + response (google.devtools.cloudbuild_v1.types.ListBuildsResponse): + 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 = cloudbuild.ListBuildsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[cloudbuild.ListBuildsResponse]: + 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) -> Iterable[cloudbuild.Build]: + for page in self.pages: + yield from page.builds + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBuildsAsyncPager: + """A pager for iterating through ``list_builds`` requests. + + This class thinly wraps an initial + :class:`google.devtools.cloudbuild_v1.types.ListBuildsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``builds`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBuilds`` requests and continue to iterate + through the ``builds`` field on the + corresponding responses. + + All the usual :class:`google.devtools.cloudbuild_v1.types.ListBuildsResponse` + 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[cloudbuild.ListBuildsResponse]], + request: cloudbuild.ListBuildsRequest, + response: cloudbuild.ListBuildsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.devtools.cloudbuild_v1.types.ListBuildsRequest): + The initial request object. + response (google.devtools.cloudbuild_v1.types.ListBuildsResponse): + 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 = cloudbuild.ListBuildsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[cloudbuild.ListBuildsResponse]: + 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) -> AsyncIterable[cloudbuild.Build]: + async def async_generator(): + async for page in self.pages: + for response in page.builds: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBuildTriggersPager: + """A pager for iterating through ``list_build_triggers`` requests. + + This class thinly wraps an initial + :class:`google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``triggers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBuildTriggers`` requests and continue to iterate + through the ``triggers`` field on the + corresponding responses. + + All the usual :class:`google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse` + 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[..., cloudbuild.ListBuildTriggersResponse], + request: cloudbuild.ListBuildTriggersRequest, + response: cloudbuild.ListBuildTriggersResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.devtools.cloudbuild_v1.types.ListBuildTriggersRequest): + The initial request object. + response (google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse): + 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 = cloudbuild.ListBuildTriggersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[cloudbuild.ListBuildTriggersResponse]: + 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) -> Iterable[cloudbuild.BuildTrigger]: + for page in self.pages: + yield from page.triggers + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBuildTriggersAsyncPager: + """A pager for iterating through ``list_build_triggers`` requests. + + This class thinly wraps an initial + :class:`google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``triggers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBuildTriggers`` requests and continue to iterate + through the ``triggers`` field on the + corresponding responses. + + All the usual :class:`google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse` + 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[cloudbuild.ListBuildTriggersResponse]], + request: cloudbuild.ListBuildTriggersRequest, + response: cloudbuild.ListBuildTriggersResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.devtools.cloudbuild_v1.types.ListBuildTriggersRequest): + The initial request object. + response (google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse): + 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 = cloudbuild.ListBuildTriggersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[cloudbuild.ListBuildTriggersResponse]: + 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) -> AsyncIterable[cloudbuild.BuildTrigger]: + async def async_generator(): + async for page in self.pages: + for response in page.triggers: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkerPoolsPager: + """A pager for iterating through ``list_worker_pools`` requests. + + This class thinly wraps an initial + :class:`google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``worker_pools`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkerPools`` requests and continue to iterate + through the ``worker_pools`` field on the + corresponding responses. + + All the usual :class:`google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse` + 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[..., cloudbuild.ListWorkerPoolsResponse], + request: cloudbuild.ListWorkerPoolsRequest, + response: cloudbuild.ListWorkerPoolsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.devtools.cloudbuild_v1.types.ListWorkerPoolsRequest): + The initial request object. + response (google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse): + 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 = cloudbuild.ListWorkerPoolsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[cloudbuild.ListWorkerPoolsResponse]: + 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) -> Iterable[cloudbuild.WorkerPool]: + for page in self.pages: + yield from page.worker_pools + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkerPoolsAsyncPager: + """A pager for iterating through ``list_worker_pools`` requests. + + This class thinly wraps an initial + :class:`google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``worker_pools`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkerPools`` requests and continue to iterate + through the ``worker_pools`` field on the + corresponding responses. + + All the usual :class:`google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse` + 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[cloudbuild.ListWorkerPoolsResponse]], + request: cloudbuild.ListWorkerPoolsRequest, + response: cloudbuild.ListWorkerPoolsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.devtools.cloudbuild_v1.types.ListWorkerPoolsRequest): + The initial request object. + response (google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse): + 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 = cloudbuild.ListWorkerPoolsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[cloudbuild.ListWorkerPoolsResponse]: + 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) -> AsyncIterable[cloudbuild.WorkerPool]: + async def async_generator(): + async for page in self.pages: + for response in page.worker_pools: + 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/devtools/cloudbuild_v1/services/cloud_build/transports/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/__init__.py new file mode 100644 index 00000000..bc5e8ed5 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CloudBuildTransport +from .grpc import CloudBuildGrpcTransport +from .grpc_asyncio import CloudBuildGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CloudBuildTransport]] +_transport_registry['grpc'] = CloudBuildGrpcTransport +_transport_registry['grpc_asyncio'] = CloudBuildGrpcAsyncIOTransport + +__all__ = ( + 'CloudBuildTransport', + 'CloudBuildGrpcTransport', + 'CloudBuildGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/base.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/base.py new file mode 100644 index 00000000..d62de80e --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/base.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.devtools.cloudbuild_v1.types import cloudbuild +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-devtools-cloudbuild', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class CloudBuildTransport(abc.ABC): + """Abstract transport class for CloudBuild.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'cloudbuild.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_build: gapic_v1.method.wrap_method( + self.create_build, + default_timeout=600.0, + client_info=client_info, + ), + self.get_build: gapic_v1.method.wrap_method( + self.get_build, + 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.list_builds: gapic_v1.method.wrap_method( + self.list_builds, + 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.cancel_build: gapic_v1.method.wrap_method( + self.cancel_build, + default_timeout=600.0, + client_info=client_info, + ), + self.retry_build: gapic_v1.method.wrap_method( + self.retry_build, + default_timeout=600.0, + client_info=client_info, + ), + self.create_build_trigger: gapic_v1.method.wrap_method( + self.create_build_trigger, + default_timeout=600.0, + client_info=client_info, + ), + self.get_build_trigger: gapic_v1.method.wrap_method( + self.get_build_trigger, + 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.list_build_triggers: gapic_v1.method.wrap_method( + self.list_build_triggers, + 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_build_trigger: gapic_v1.method.wrap_method( + self.delete_build_trigger, + 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.update_build_trigger: gapic_v1.method.wrap_method( + self.update_build_trigger, + default_timeout=600.0, + client_info=client_info, + ), + self.run_build_trigger: gapic_v1.method.wrap_method( + self.run_build_trigger, + default_timeout=600.0, + client_info=client_info, + ), + self.receive_trigger_webhook: gapic_v1.method.wrap_method( + self.receive_trigger_webhook, + default_timeout=None, + client_info=client_info, + ), + self.create_worker_pool: gapic_v1.method.wrap_method( + self.create_worker_pool, + default_timeout=600.0, + client_info=client_info, + ), + self.get_worker_pool: gapic_v1.method.wrap_method( + self.get_worker_pool, + 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_worker_pool: gapic_v1.method.wrap_method( + self.delete_worker_pool, + default_timeout=600.0, + client_info=client_info, + ), + self.update_worker_pool: gapic_v1.method.wrap_method( + self.update_worker_pool, + default_timeout=600.0, + client_info=client_info, + ), + self.list_worker_pools: gapic_v1.method.wrap_method( + self.list_worker_pools, + 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, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_build(self) -> Callable[ + [cloudbuild.CreateBuildRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_build(self) -> Callable[ + [cloudbuild.GetBuildRequest], + Union[ + cloudbuild.Build, + Awaitable[cloudbuild.Build] + ]]: + raise NotImplementedError() + + @property + def list_builds(self) -> Callable[ + [cloudbuild.ListBuildsRequest], + Union[ + cloudbuild.ListBuildsResponse, + Awaitable[cloudbuild.ListBuildsResponse] + ]]: + raise NotImplementedError() + + @property + def cancel_build(self) -> Callable[ + [cloudbuild.CancelBuildRequest], + Union[ + cloudbuild.Build, + Awaitable[cloudbuild.Build] + ]]: + raise NotImplementedError() + + @property + def retry_build(self) -> Callable[ + [cloudbuild.RetryBuildRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_build_trigger(self) -> Callable[ + [cloudbuild.CreateBuildTriggerRequest], + Union[ + cloudbuild.BuildTrigger, + Awaitable[cloudbuild.BuildTrigger] + ]]: + raise NotImplementedError() + + @property + def get_build_trigger(self) -> Callable[ + [cloudbuild.GetBuildTriggerRequest], + Union[ + cloudbuild.BuildTrigger, + Awaitable[cloudbuild.BuildTrigger] + ]]: + raise NotImplementedError() + + @property + def list_build_triggers(self) -> Callable[ + [cloudbuild.ListBuildTriggersRequest], + Union[ + cloudbuild.ListBuildTriggersResponse, + Awaitable[cloudbuild.ListBuildTriggersResponse] + ]]: + raise NotImplementedError() + + @property + def delete_build_trigger(self) -> Callable[ + [cloudbuild.DeleteBuildTriggerRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_build_trigger(self) -> Callable[ + [cloudbuild.UpdateBuildTriggerRequest], + Union[ + cloudbuild.BuildTrigger, + Awaitable[cloudbuild.BuildTrigger] + ]]: + raise NotImplementedError() + + @property + def run_build_trigger(self) -> Callable[ + [cloudbuild.RunBuildTriggerRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def receive_trigger_webhook(self) -> Callable[ + [cloudbuild.ReceiveTriggerWebhookRequest], + Union[ + cloudbuild.ReceiveTriggerWebhookResponse, + Awaitable[cloudbuild.ReceiveTriggerWebhookResponse] + ]]: + raise NotImplementedError() + + @property + def create_worker_pool(self) -> Callable[ + [cloudbuild.CreateWorkerPoolRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_worker_pool(self) -> Callable[ + [cloudbuild.GetWorkerPoolRequest], + Union[ + cloudbuild.WorkerPool, + Awaitable[cloudbuild.WorkerPool] + ]]: + raise NotImplementedError() + + @property + def delete_worker_pool(self) -> Callable[ + [cloudbuild.DeleteWorkerPoolRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_worker_pool(self) -> Callable[ + [cloudbuild.UpdateWorkerPoolRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_worker_pools(self) -> Callable[ + [cloudbuild.ListWorkerPoolsRequest], + Union[ + cloudbuild.ListWorkerPoolsResponse, + Awaitable[cloudbuild.ListWorkerPoolsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'CloudBuildTransport', +) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc.py new file mode 100644 index 00000000..70a55a7f --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc.py @@ -0,0 +1,745 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.devtools.cloudbuild_v1.types import cloudbuild +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import CloudBuildTransport, DEFAULT_CLIENT_INFO + + +class CloudBuildGrpcTransport(CloudBuildTransport): + """gRPC backend transport for CloudBuild. + + Creates and manages builds on Google Cloud Platform. + + The main concept used by this API is a ``Build``, which describes + the location of the source to build, how to build the source, and + where to store the built artifacts, if any. + + A user can list previously-requested builds or get builds by their + ID to determine the status of the build. + + 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 = 'cloudbuild.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin 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 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 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 = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudbuild.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. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_build(self) -> Callable[ + [cloudbuild.CreateBuildRequest], + operations_pb2.Operation]: + r"""Return a callable for the create build method over gRPC. + + Starts a build with the specified configuration. + + This method returns a long-running ``Operation``, which includes + the build ID. Pass the build ID to ``GetBuild`` to determine the + build status (such as ``SUCCESS`` or ``FAILURE``). + + Returns: + Callable[[~.CreateBuildRequest], + ~.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_build' not in self._stubs: + self._stubs['create_build'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/CreateBuild', + request_serializer=cloudbuild.CreateBuildRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_build'] + + @property + def get_build(self) -> Callable[ + [cloudbuild.GetBuildRequest], + cloudbuild.Build]: + r"""Return a callable for the get build method over gRPC. + + Returns information about a previously requested build. + + The ``Build`` that is returned includes its status (such as + ``SUCCESS``, ``FAILURE``, or ``WORKING``), and timing + information. + + Returns: + Callable[[~.GetBuildRequest], + ~.Build]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_build' not in self._stubs: + self._stubs['get_build'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/GetBuild', + request_serializer=cloudbuild.GetBuildRequest.serialize, + response_deserializer=cloudbuild.Build.deserialize, + ) + return self._stubs['get_build'] + + @property + def list_builds(self) -> Callable[ + [cloudbuild.ListBuildsRequest], + cloudbuild.ListBuildsResponse]: + r"""Return a callable for the list builds method over gRPC. + + Lists previously requested builds. + Previously requested builds may still be in-progress, or + may have finished successfully or unsuccessfully. + + Returns: + Callable[[~.ListBuildsRequest], + ~.ListBuildsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_builds' not in self._stubs: + self._stubs['list_builds'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/ListBuilds', + request_serializer=cloudbuild.ListBuildsRequest.serialize, + response_deserializer=cloudbuild.ListBuildsResponse.deserialize, + ) + return self._stubs['list_builds'] + + @property + def cancel_build(self) -> Callable[ + [cloudbuild.CancelBuildRequest], + cloudbuild.Build]: + r"""Return a callable for the cancel build method over gRPC. + + Cancels a build in progress. + + Returns: + Callable[[~.CancelBuildRequest], + ~.Build]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'cancel_build' not in self._stubs: + self._stubs['cancel_build'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/CancelBuild', + request_serializer=cloudbuild.CancelBuildRequest.serialize, + response_deserializer=cloudbuild.Build.deserialize, + ) + return self._stubs['cancel_build'] + + @property + def retry_build(self) -> Callable[ + [cloudbuild.RetryBuildRequest], + operations_pb2.Operation]: + r"""Return a callable for the retry build method over gRPC. + + Creates a new build based on the specified build. + + This method creates a new build using the original build + request, which may or may not result in an identical build. + + For triggered builds: + + - Triggered builds resolve to a precise revision; therefore a + retry of a triggered build will result in a build that uses + the same revision. + + For non-triggered builds that specify ``RepoSource``: + + - If the original build built from the tip of a branch, the + retried build will build from the tip of that branch, which + may not be the same revision as the original build. + - If the original build specified a commit sha or revision ID, + the retried build will use the identical source. + + For builds that specify ``StorageSource``: + + - If the original build pulled source from Google Cloud Storage + without specifying the generation of the object, the new + build will use the current object, which may be different + from the original build source. + - If the original build pulled source from Cloud Storage and + specified the generation of the object, the new build will + attempt to use the same object, which may or may not be + available depending on the bucket's lifecycle management + settings. + + Returns: + Callable[[~.RetryBuildRequest], + ~.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 'retry_build' not in self._stubs: + self._stubs['retry_build'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/RetryBuild', + request_serializer=cloudbuild.RetryBuildRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['retry_build'] + + @property + def create_build_trigger(self) -> Callable[ + [cloudbuild.CreateBuildTriggerRequest], + cloudbuild.BuildTrigger]: + r"""Return a callable for the create build trigger method over gRPC. + + Creates a new ``BuildTrigger``. + + This API is experimental. + + Returns: + Callable[[~.CreateBuildTriggerRequest], + ~.BuildTrigger]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: + self._stubs['create_build_trigger'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/CreateBuildTrigger', + request_serializer=cloudbuild.CreateBuildTriggerRequest.serialize, + response_deserializer=cloudbuild.BuildTrigger.deserialize, + ) + return self._stubs['create_build_trigger'] + + @property + def get_build_trigger(self) -> Callable[ + [cloudbuild.GetBuildTriggerRequest], + cloudbuild.BuildTrigger]: + r"""Return a callable for the get build trigger method over gRPC. + + Returns information about a ``BuildTrigger``. + + This API is experimental. + + Returns: + Callable[[~.GetBuildTriggerRequest], + ~.BuildTrigger]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: + self._stubs['get_build_trigger'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/GetBuildTrigger', + request_serializer=cloudbuild.GetBuildTriggerRequest.serialize, + response_deserializer=cloudbuild.BuildTrigger.deserialize, + ) + return self._stubs['get_build_trigger'] + + @property + def list_build_triggers(self) -> Callable[ + [cloudbuild.ListBuildTriggersRequest], + cloudbuild.ListBuildTriggersResponse]: + r"""Return a callable for the list build triggers method over gRPC. + + Lists existing ``BuildTrigger``\ s. + + This API is experimental. + + Returns: + Callable[[~.ListBuildTriggersRequest], + ~.ListBuildTriggersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_build_triggers' not in self._stubs: + self._stubs['list_build_triggers'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/ListBuildTriggers', + request_serializer=cloudbuild.ListBuildTriggersRequest.serialize, + response_deserializer=cloudbuild.ListBuildTriggersResponse.deserialize, + ) + return self._stubs['list_build_triggers'] + + @property + def delete_build_trigger(self) -> Callable[ + [cloudbuild.DeleteBuildTriggerRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete build trigger method over gRPC. + + Deletes a ``BuildTrigger`` by its project ID and trigger ID. + + This API is experimental. + + Returns: + Callable[[~.DeleteBuildTriggerRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_build_trigger' not in self._stubs: + self._stubs['delete_build_trigger'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/DeleteBuildTrigger', + request_serializer=cloudbuild.DeleteBuildTriggerRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_build_trigger'] + + @property + def update_build_trigger(self) -> Callable[ + [cloudbuild.UpdateBuildTriggerRequest], + cloudbuild.BuildTrigger]: + r"""Return a callable for the update build trigger method over gRPC. + + Updates a ``BuildTrigger`` by its project ID and trigger ID. + + This API is experimental. + + Returns: + Callable[[~.UpdateBuildTriggerRequest], + ~.BuildTrigger]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: + self._stubs['update_build_trigger'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/UpdateBuildTrigger', + request_serializer=cloudbuild.UpdateBuildTriggerRequest.serialize, + response_deserializer=cloudbuild.BuildTrigger.deserialize, + ) + return self._stubs['update_build_trigger'] + + @property + def run_build_trigger(self) -> Callable[ + [cloudbuild.RunBuildTriggerRequest], + operations_pb2.Operation]: + r"""Return a callable for the run build trigger method over gRPC. + + Runs a ``BuildTrigger`` at a particular source revision. + + Returns: + Callable[[~.RunBuildTriggerRequest], + ~.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 'run_build_trigger' not in self._stubs: + self._stubs['run_build_trigger'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/RunBuildTrigger', + request_serializer=cloudbuild.RunBuildTriggerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_build_trigger'] + + @property + def receive_trigger_webhook(self) -> Callable[ + [cloudbuild.ReceiveTriggerWebhookRequest], + cloudbuild.ReceiveTriggerWebhookResponse]: + r"""Return a callable for the receive trigger webhook method over gRPC. + + ReceiveTriggerWebhook [Experimental] is called when the API + receives a webhook request targeted at a specific trigger. + + Returns: + Callable[[~.ReceiveTriggerWebhookRequest], + ~.ReceiveTriggerWebhookResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'receive_trigger_webhook' not in self._stubs: + self._stubs['receive_trigger_webhook'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/ReceiveTriggerWebhook', + request_serializer=cloudbuild.ReceiveTriggerWebhookRequest.serialize, + response_deserializer=cloudbuild.ReceiveTriggerWebhookResponse.deserialize, + ) + return self._stubs['receive_trigger_webhook'] + + @property + def create_worker_pool(self) -> Callable[ + [cloudbuild.CreateWorkerPoolRequest], + operations_pb2.Operation]: + r"""Return a callable for the create worker pool method over gRPC. + + Creates a ``WorkerPool``. + + Returns: + Callable[[~.CreateWorkerPoolRequest], + ~.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_worker_pool' not in self._stubs: + self._stubs['create_worker_pool'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/CreateWorkerPool', + request_serializer=cloudbuild.CreateWorkerPoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_worker_pool'] + + @property + def get_worker_pool(self) -> Callable[ + [cloudbuild.GetWorkerPoolRequest], + cloudbuild.WorkerPool]: + r"""Return a callable for the get worker pool method over gRPC. + + Returns details of a ``WorkerPool``. + + Returns: + Callable[[~.GetWorkerPoolRequest], + ~.WorkerPool]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_worker_pool' not in self._stubs: + self._stubs['get_worker_pool'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/GetWorkerPool', + request_serializer=cloudbuild.GetWorkerPoolRequest.serialize, + response_deserializer=cloudbuild.WorkerPool.deserialize, + ) + return self._stubs['get_worker_pool'] + + @property + def delete_worker_pool(self) -> Callable[ + [cloudbuild.DeleteWorkerPoolRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete worker pool method over gRPC. + + Deletes a ``WorkerPool``. + + Returns: + Callable[[~.DeleteWorkerPoolRequest], + ~.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_worker_pool' not in self._stubs: + self._stubs['delete_worker_pool'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/DeleteWorkerPool', + request_serializer=cloudbuild.DeleteWorkerPoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_worker_pool'] + + @property + def update_worker_pool(self) -> Callable[ + [cloudbuild.UpdateWorkerPoolRequest], + operations_pb2.Operation]: + r"""Return a callable for the update worker pool method over gRPC. + + Updates a ``WorkerPool``. + + Returns: + Callable[[~.UpdateWorkerPoolRequest], + ~.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_worker_pool' not in self._stubs: + self._stubs['update_worker_pool'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/UpdateWorkerPool', + request_serializer=cloudbuild.UpdateWorkerPoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_worker_pool'] + + @property + def list_worker_pools(self) -> Callable[ + [cloudbuild.ListWorkerPoolsRequest], + cloudbuild.ListWorkerPoolsResponse]: + r"""Return a callable for the list worker pools method over gRPC. + + Lists ``WorkerPool``\ s. + + Returns: + Callable[[~.ListWorkerPoolsRequest], + ~.ListWorkerPoolsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_worker_pools' not in self._stubs: + self._stubs['list_worker_pools'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/ListWorkerPools', + request_serializer=cloudbuild.ListWorkerPoolsRequest.serialize, + response_deserializer=cloudbuild.ListWorkerPoolsResponse.deserialize, + ) + return self._stubs['list_worker_pools'] + + +__all__ = ( + 'CloudBuildGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc_asyncio.py new file mode 100644 index 00000000..b1f3a881 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc_asyncio.py @@ -0,0 +1,749 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.devtools.cloudbuild_v1.types import cloudbuild +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import CloudBuildTransport, DEFAULT_CLIENT_INFO +from .grpc import CloudBuildGrpcTransport + + +class CloudBuildGrpcAsyncIOTransport(CloudBuildTransport): + """gRPC AsyncIO backend transport for CloudBuild. + + Creates and manages builds on Google Cloud Platform. + + The main concept used by this API is a ``Build``, which describes + the location of the source to build, how to build the source, and + where to store the built artifacts, if any. + + A user can list previously-requested builds or get builds by their + ID to determine the status of the build. + + 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 = 'cloudbuild.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 = 'cloudbuild.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin 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 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 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 = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_build(self) -> Callable[ + [cloudbuild.CreateBuildRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create build method over gRPC. + + Starts a build with the specified configuration. + + This method returns a long-running ``Operation``, which includes + the build ID. Pass the build ID to ``GetBuild`` to determine the + build status (such as ``SUCCESS`` or ``FAILURE``). + + Returns: + Callable[[~.CreateBuildRequest], + 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_build' not in self._stubs: + self._stubs['create_build'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/CreateBuild', + request_serializer=cloudbuild.CreateBuildRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_build'] + + @property + def get_build(self) -> Callable[ + [cloudbuild.GetBuildRequest], + Awaitable[cloudbuild.Build]]: + r"""Return a callable for the get build method over gRPC. + + Returns information about a previously requested build. + + The ``Build`` that is returned includes its status (such as + ``SUCCESS``, ``FAILURE``, or ``WORKING``), and timing + information. + + Returns: + Callable[[~.GetBuildRequest], + Awaitable[~.Build]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_build' not in self._stubs: + self._stubs['get_build'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/GetBuild', + request_serializer=cloudbuild.GetBuildRequest.serialize, + response_deserializer=cloudbuild.Build.deserialize, + ) + return self._stubs['get_build'] + + @property + def list_builds(self) -> Callable[ + [cloudbuild.ListBuildsRequest], + Awaitable[cloudbuild.ListBuildsResponse]]: + r"""Return a callable for the list builds method over gRPC. + + Lists previously requested builds. + Previously requested builds may still be in-progress, or + may have finished successfully or unsuccessfully. + + Returns: + Callable[[~.ListBuildsRequest], + Awaitable[~.ListBuildsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_builds' not in self._stubs: + self._stubs['list_builds'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/ListBuilds', + request_serializer=cloudbuild.ListBuildsRequest.serialize, + response_deserializer=cloudbuild.ListBuildsResponse.deserialize, + ) + return self._stubs['list_builds'] + + @property + def cancel_build(self) -> Callable[ + [cloudbuild.CancelBuildRequest], + Awaitable[cloudbuild.Build]]: + r"""Return a callable for the cancel build method over gRPC. + + Cancels a build in progress. + + Returns: + Callable[[~.CancelBuildRequest], + Awaitable[~.Build]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'cancel_build' not in self._stubs: + self._stubs['cancel_build'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/CancelBuild', + request_serializer=cloudbuild.CancelBuildRequest.serialize, + response_deserializer=cloudbuild.Build.deserialize, + ) + return self._stubs['cancel_build'] + + @property + def retry_build(self) -> Callable[ + [cloudbuild.RetryBuildRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the retry build method over gRPC. + + Creates a new build based on the specified build. + + This method creates a new build using the original build + request, which may or may not result in an identical build. + + For triggered builds: + + - Triggered builds resolve to a precise revision; therefore a + retry of a triggered build will result in a build that uses + the same revision. + + For non-triggered builds that specify ``RepoSource``: + + - If the original build built from the tip of a branch, the + retried build will build from the tip of that branch, which + may not be the same revision as the original build. + - If the original build specified a commit sha or revision ID, + the retried build will use the identical source. + + For builds that specify ``StorageSource``: + + - If the original build pulled source from Google Cloud Storage + without specifying the generation of the object, the new + build will use the current object, which may be different + from the original build source. + - If the original build pulled source from Cloud Storage and + specified the generation of the object, the new build will + attempt to use the same object, which may or may not be + available depending on the bucket's lifecycle management + settings. + + Returns: + Callable[[~.RetryBuildRequest], + 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 'retry_build' not in self._stubs: + self._stubs['retry_build'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/RetryBuild', + request_serializer=cloudbuild.RetryBuildRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['retry_build'] + + @property + def create_build_trigger(self) -> Callable[ + [cloudbuild.CreateBuildTriggerRequest], + Awaitable[cloudbuild.BuildTrigger]]: + r"""Return a callable for the create build trigger method over gRPC. + + Creates a new ``BuildTrigger``. + + This API is experimental. + + Returns: + Callable[[~.CreateBuildTriggerRequest], + Awaitable[~.BuildTrigger]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: + self._stubs['create_build_trigger'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/CreateBuildTrigger', + request_serializer=cloudbuild.CreateBuildTriggerRequest.serialize, + response_deserializer=cloudbuild.BuildTrigger.deserialize, + ) + return self._stubs['create_build_trigger'] + + @property + def get_build_trigger(self) -> Callable[ + [cloudbuild.GetBuildTriggerRequest], + Awaitable[cloudbuild.BuildTrigger]]: + r"""Return a callable for the get build trigger method over gRPC. + + Returns information about a ``BuildTrigger``. + + This API is experimental. + + Returns: + Callable[[~.GetBuildTriggerRequest], + Awaitable[~.BuildTrigger]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: + self._stubs['get_build_trigger'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/GetBuildTrigger', + request_serializer=cloudbuild.GetBuildTriggerRequest.serialize, + response_deserializer=cloudbuild.BuildTrigger.deserialize, + ) + return self._stubs['get_build_trigger'] + + @property + def list_build_triggers(self) -> Callable[ + [cloudbuild.ListBuildTriggersRequest], + Awaitable[cloudbuild.ListBuildTriggersResponse]]: + r"""Return a callable for the list build triggers method over gRPC. + + Lists existing ``BuildTrigger``\ s. + + This API is experimental. + + Returns: + Callable[[~.ListBuildTriggersRequest], + Awaitable[~.ListBuildTriggersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_build_triggers' not in self._stubs: + self._stubs['list_build_triggers'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/ListBuildTriggers', + request_serializer=cloudbuild.ListBuildTriggersRequest.serialize, + response_deserializer=cloudbuild.ListBuildTriggersResponse.deserialize, + ) + return self._stubs['list_build_triggers'] + + @property + def delete_build_trigger(self) -> Callable[ + [cloudbuild.DeleteBuildTriggerRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete build trigger method over gRPC. + + Deletes a ``BuildTrigger`` by its project ID and trigger ID. + + This API is experimental. + + Returns: + Callable[[~.DeleteBuildTriggerRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_build_trigger' not in self._stubs: + self._stubs['delete_build_trigger'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/DeleteBuildTrigger', + request_serializer=cloudbuild.DeleteBuildTriggerRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_build_trigger'] + + @property + def update_build_trigger(self) -> Callable[ + [cloudbuild.UpdateBuildTriggerRequest], + Awaitable[cloudbuild.BuildTrigger]]: + r"""Return a callable for the update build trigger method over gRPC. + + Updates a ``BuildTrigger`` by its project ID and trigger ID. + + This API is experimental. + + Returns: + Callable[[~.UpdateBuildTriggerRequest], + Awaitable[~.BuildTrigger]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: + self._stubs['update_build_trigger'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/UpdateBuildTrigger', + request_serializer=cloudbuild.UpdateBuildTriggerRequest.serialize, + response_deserializer=cloudbuild.BuildTrigger.deserialize, + ) + return self._stubs['update_build_trigger'] + + @property + def run_build_trigger(self) -> Callable[ + [cloudbuild.RunBuildTriggerRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run build trigger method over gRPC. + + Runs a ``BuildTrigger`` at a particular source revision. + + Returns: + Callable[[~.RunBuildTriggerRequest], + 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 'run_build_trigger' not in self._stubs: + self._stubs['run_build_trigger'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/RunBuildTrigger', + request_serializer=cloudbuild.RunBuildTriggerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_build_trigger'] + + @property + def receive_trigger_webhook(self) -> Callable[ + [cloudbuild.ReceiveTriggerWebhookRequest], + Awaitable[cloudbuild.ReceiveTriggerWebhookResponse]]: + r"""Return a callable for the receive trigger webhook method over gRPC. + + ReceiveTriggerWebhook [Experimental] is called when the API + receives a webhook request targeted at a specific trigger. + + Returns: + Callable[[~.ReceiveTriggerWebhookRequest], + Awaitable[~.ReceiveTriggerWebhookResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'receive_trigger_webhook' not in self._stubs: + self._stubs['receive_trigger_webhook'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/ReceiveTriggerWebhook', + request_serializer=cloudbuild.ReceiveTriggerWebhookRequest.serialize, + response_deserializer=cloudbuild.ReceiveTriggerWebhookResponse.deserialize, + ) + return self._stubs['receive_trigger_webhook'] + + @property + def create_worker_pool(self) -> Callable[ + [cloudbuild.CreateWorkerPoolRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create worker pool method over gRPC. + + Creates a ``WorkerPool``. + + Returns: + Callable[[~.CreateWorkerPoolRequest], + 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_worker_pool' not in self._stubs: + self._stubs['create_worker_pool'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/CreateWorkerPool', + request_serializer=cloudbuild.CreateWorkerPoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_worker_pool'] + + @property + def get_worker_pool(self) -> Callable[ + [cloudbuild.GetWorkerPoolRequest], + Awaitable[cloudbuild.WorkerPool]]: + r"""Return a callable for the get worker pool method over gRPC. + + Returns details of a ``WorkerPool``. + + Returns: + Callable[[~.GetWorkerPoolRequest], + Awaitable[~.WorkerPool]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_worker_pool' not in self._stubs: + self._stubs['get_worker_pool'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/GetWorkerPool', + request_serializer=cloudbuild.GetWorkerPoolRequest.serialize, + response_deserializer=cloudbuild.WorkerPool.deserialize, + ) + return self._stubs['get_worker_pool'] + + @property + def delete_worker_pool(self) -> Callable[ + [cloudbuild.DeleteWorkerPoolRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete worker pool method over gRPC. + + Deletes a ``WorkerPool``. + + Returns: + Callable[[~.DeleteWorkerPoolRequest], + 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_worker_pool' not in self._stubs: + self._stubs['delete_worker_pool'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/DeleteWorkerPool', + request_serializer=cloudbuild.DeleteWorkerPoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_worker_pool'] + + @property + def update_worker_pool(self) -> Callable[ + [cloudbuild.UpdateWorkerPoolRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update worker pool method over gRPC. + + Updates a ``WorkerPool``. + + Returns: + Callable[[~.UpdateWorkerPoolRequest], + 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_worker_pool' not in self._stubs: + self._stubs['update_worker_pool'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/UpdateWorkerPool', + request_serializer=cloudbuild.UpdateWorkerPoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_worker_pool'] + + @property + def list_worker_pools(self) -> Callable[ + [cloudbuild.ListWorkerPoolsRequest], + Awaitable[cloudbuild.ListWorkerPoolsResponse]]: + r"""Return a callable for the list worker pools method over gRPC. + + Lists ``WorkerPool``\ s. + + Returns: + Callable[[~.ListWorkerPoolsRequest], + Awaitable[~.ListWorkerPoolsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_worker_pools' not in self._stubs: + self._stubs['list_worker_pools'] = self.grpc_channel.unary_unary( + '/google.devtools.cloudbuild.v1.CloudBuild/ListWorkerPools', + request_serializer=cloudbuild.ListWorkerPoolsRequest.serialize, + response_deserializer=cloudbuild.ListWorkerPoolsResponse.deserialize, + ) + return self._stubs['list_worker_pools'] + + +__all__ = ( + 'CloudBuildGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/__init__.py new file mode 100644 index 00000000..b09050ee --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/__init__.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .cloudbuild import ( + ArtifactResult, + Artifacts, + Build, + BuildOperationMetadata, + BuildOptions, + BuildStep, + BuildTrigger, + BuiltImage, + CancelBuildRequest, + CreateBuildRequest, + CreateBuildTriggerRequest, + CreateWorkerPoolOperationMetadata, + CreateWorkerPoolRequest, + DeleteBuildTriggerRequest, + DeleteWorkerPoolOperationMetadata, + DeleteWorkerPoolRequest, + FileHashes, + GetBuildRequest, + GetBuildTriggerRequest, + GetWorkerPoolRequest, + GitHubEventsConfig, + Hash, + InlineSecret, + ListBuildsRequest, + ListBuildsResponse, + ListBuildTriggersRequest, + ListBuildTriggersResponse, + ListWorkerPoolsRequest, + ListWorkerPoolsResponse, + PrivatePoolV1Config, + PubsubConfig, + PullRequestFilter, + PushFilter, + ReceiveTriggerWebhookRequest, + ReceiveTriggerWebhookResponse, + RepoSource, + Results, + RetryBuildRequest, + RunBuildTriggerRequest, + Secret, + SecretManagerSecret, + Secrets, + Source, + SourceProvenance, + StorageSource, + StorageSourceManifest, + TimeSpan, + UpdateBuildTriggerRequest, + UpdateWorkerPoolOperationMetadata, + UpdateWorkerPoolRequest, + Volume, + WebhookConfig, + WorkerPool, +) + +__all__ = ( + 'ArtifactResult', + 'Artifacts', + 'Build', + 'BuildOperationMetadata', + 'BuildOptions', + 'BuildStep', + 'BuildTrigger', + 'BuiltImage', + 'CancelBuildRequest', + 'CreateBuildRequest', + 'CreateBuildTriggerRequest', + 'CreateWorkerPoolOperationMetadata', + 'CreateWorkerPoolRequest', + 'DeleteBuildTriggerRequest', + 'DeleteWorkerPoolOperationMetadata', + 'DeleteWorkerPoolRequest', + 'FileHashes', + 'GetBuildRequest', + 'GetBuildTriggerRequest', + 'GetWorkerPoolRequest', + 'GitHubEventsConfig', + 'Hash', + 'InlineSecret', + 'ListBuildsRequest', + 'ListBuildsResponse', + 'ListBuildTriggersRequest', + 'ListBuildTriggersResponse', + 'ListWorkerPoolsRequest', + 'ListWorkerPoolsResponse', + 'PrivatePoolV1Config', + 'PubsubConfig', + 'PullRequestFilter', + 'PushFilter', + 'ReceiveTriggerWebhookRequest', + 'ReceiveTriggerWebhookResponse', + 'RepoSource', + 'Results', + 'RetryBuildRequest', + 'RunBuildTriggerRequest', + 'Secret', + 'SecretManagerSecret', + 'Secrets', + 'Source', + 'SourceProvenance', + 'StorageSource', + 'StorageSourceManifest', + 'TimeSpan', + 'UpdateBuildTriggerRequest', + 'UpdateWorkerPoolOperationMetadata', + 'UpdateWorkerPoolRequest', + 'Volume', + 'WebhookConfig', + 'WorkerPool', +) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/cloudbuild.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/cloudbuild.py new file mode 100644 index 00000000..d5c68665 --- /dev/null +++ b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/cloudbuild.py @@ -0,0 +1,2693 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.api import httpbody_pb2 # 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.devtools.cloudbuild.v1', + manifest={ + 'RetryBuildRequest', + 'RunBuildTriggerRequest', + 'StorageSource', + 'RepoSource', + 'StorageSourceManifest', + 'Source', + 'BuiltImage', + 'BuildStep', + 'Volume', + 'Results', + 'ArtifactResult', + 'Build', + 'Artifacts', + 'TimeSpan', + 'BuildOperationMetadata', + 'SourceProvenance', + 'FileHashes', + 'Hash', + 'Secrets', + 'InlineSecret', + 'SecretManagerSecret', + 'Secret', + 'CreateBuildRequest', + 'GetBuildRequest', + 'ListBuildsRequest', + 'ListBuildsResponse', + 'CancelBuildRequest', + 'BuildTrigger', + 'GitHubEventsConfig', + 'PubsubConfig', + 'WebhookConfig', + 'PullRequestFilter', + 'PushFilter', + 'CreateBuildTriggerRequest', + 'GetBuildTriggerRequest', + 'ListBuildTriggersRequest', + 'ListBuildTriggersResponse', + 'DeleteBuildTriggerRequest', + 'UpdateBuildTriggerRequest', + 'BuildOptions', + 'ReceiveTriggerWebhookRequest', + 'ReceiveTriggerWebhookResponse', + 'WorkerPool', + 'PrivatePoolV1Config', + 'CreateWorkerPoolRequest', + 'GetWorkerPoolRequest', + 'DeleteWorkerPoolRequest', + 'UpdateWorkerPoolRequest', + 'ListWorkerPoolsRequest', + 'ListWorkerPoolsResponse', + 'CreateWorkerPoolOperationMetadata', + 'UpdateWorkerPoolOperationMetadata', + 'DeleteWorkerPoolOperationMetadata', + }, +) + + +class RetryBuildRequest(proto.Message): + r"""Specifies a build to retry. + Attributes: + name (str): + The name of the ``Build`` to retry. Format: + ``projects/{project}/locations/{location}/builds/{build}`` + project_id (str): + Required. ID of the project. + id (str): + Required. Build ID of the original build. + """ + + name = proto.Field( + proto.STRING, + number=3, + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + + +class RunBuildTriggerRequest(proto.Message): + r"""Specifies a build trigger to run and the source to use. + Attributes: + name (str): + The name of the ``Trigger`` to run. Format: + ``projects/{project}/locations/{location}/triggers/{trigger}`` + project_id (str): + Required. ID of the project. + trigger_id (str): + Required. ID of the trigger. + source (google.devtools.cloudbuild_v1.types.RepoSource): + Source to build against this trigger. + """ + + name = proto.Field( + proto.STRING, + number=4, + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + trigger_id = proto.Field( + proto.STRING, + number=2, + ) + source = proto.Field( + proto.MESSAGE, + number=3, + message='RepoSource', + ) + + +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. + Attributes: + 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. + 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 + 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 + commit_sha (str): + Explicit commit SHA to build. + 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. + invert_regex (bool): + Only trigger a build if the revision regex + does NOT match the revision regex. + substitutions (Sequence[google.devtools.cloudbuild_v1.types.RepoSource.SubstitutionsEntry]): + Substitutions to use in a triggered build. + Should only be used with RunBuildTrigger + """ + + project_id = proto.Field( + proto.STRING, + number=1, + ) + repo_name = proto.Field( + proto.STRING, + number=2, + ) + 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', + ) + dir_ = proto.Field( + proto.STRING, + number=7, + ) + invert_regex = proto.Field( + proto.BOOL, + number=8, + ) + substitutions = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + + +class StorageSourceManifest(proto.Message): + r"""Location of the source manifest in Google Cloud Storage. This + feature is in Preview; see description + `here `__. + + Attributes: + bucket (str): + Google Cloud Storage bucket containing the source manifest + (see `Bucket Name + Requirements `__). + object_ (str): + Google Cloud Storage object containing the + source manifest. + This object must be a JSON file. + 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 Source(proto.Message): + r"""Location of the source in a supported storage service. + Attributes: + storage_source (google.devtools.cloudbuild_v1.types.StorageSource): + If provided, get the source from this + location in Google Cloud Storage. + repo_source (google.devtools.cloudbuild_v1.types.RepoSource): + If provided, get the source from this + location in a Cloud Source Repository. + storage_source_manifest (google.devtools.cloudbuild_v1.types.StorageSourceManifest): + If provided, get the source from this manifest in Google + Cloud Storage. This feature is in Preview; see description + `here `__. + """ + + storage_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='StorageSource', + ) + repo_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='RepoSource', + ) + storage_source_manifest = proto.Field( + proto.MESSAGE, + number=8, + oneof='source', + message='StorageSourceManifest', + ) + + +class BuiltImage(proto.Message): + r"""An image built by the pipeline. + Attributes: + name (str): + Name used to push the container image to Google Container + Registry, as presented to ``docker push``. + digest (str): + Docker Registry 2.0 digest. + push_timing (google.devtools.cloudbuild_v1.types.TimeSpan): + Output only. Stores timing information for + pushing the specified image. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + digest = proto.Field( + proto.STRING, + number=3, + ) + push_timing = proto.Field( + proto.MESSAGE, + number=4, + message='TimeSpan', + ) + + +class BuildStep(proto.Message): + r"""A step in the build pipeline. + Attributes: + name (str): + Required. The name of the container image that will run this + particular build step. + + If the image is available in the host's Docker daemon's + cache, it will be run directly. If not, the host will + attempt to pull the image first, using the builder service + account's credentials if necessary. + + The Docker daemon's cache will already have the latest + versions of all of the officially supported build steps + (https://github.com/GoogleCloudPlatform/cloud-builders). The + Docker daemon will also have cached many of the layers for + some popular images, like "ubuntu", "debian", but they will + be refreshed at the time you attempt to use them. + + If you built an image in a previous build step, it will be + stored in the host's Docker daemon's cache and is available + to use as the name for a later build step. + env (Sequence[str]): + A list of environment variable definitions to + be used when running a step. + The elements are of the form "KEY=VALUE" for the + environment variable "KEY" being given the value + "VALUE". + args (Sequence[str]): + A list of arguments that will be presented to the step when + it is started. + + If the image used to run the step's container has an + entrypoint, the ``args`` are used as arguments to that + entrypoint. If the image does not define an entrypoint, the + first element in args is used as the entrypoint, and the + remainder will be used as arguments. + dir_ (str): + Working directory to use when running this step's container. + + If this value is a relative path, it is relative to the + build's working directory. If this value is absolute, it may + be outside the build's working directory, in which case the + contents of the path may not be persisted across build step + executions, unless a ``volume`` for that path is specified. + + If the build specifies a ``RepoSource`` with ``dir`` and a + step with a ``dir``, which specifies an absolute path, the + ``RepoSource`` ``dir`` is ignored for the step's execution. + id (str): + Unique identifier for this build step, used in ``wait_for`` + to reference this build step as a dependency. + wait_for (Sequence[str]): + The ID(s) of the step(s) that this build step depends on. + This build step will not start until all the build steps in + ``wait_for`` have completed successfully. If ``wait_for`` is + empty, this build step will start when all previous build + steps in the ``Build.Steps`` list have completed + successfully. + entrypoint (str): + Entrypoint to be used instead of the build + step image's default entrypoint. If unset, the + image's default entrypoint is used. + secret_env (Sequence[str]): + A list of environment variables which are encrypted using a + Cloud Key Management Service crypto key. These values must + be specified in the build's ``Secret``. + volumes (Sequence[google.devtools.cloudbuild_v1.types.Volume]): + List of volumes to mount into the build step. + Each volume is created as an empty volume prior + to execution of the build step. Upon completion + of the build, volumes and their contents are + discarded. + + Using a named volume in only one step is not + valid as it is indicative of a build request + with an incorrect configuration. + timing (google.devtools.cloudbuild_v1.types.TimeSpan): + Output only. Stores timing information for + executing this build step. + pull_timing (google.devtools.cloudbuild_v1.types.TimeSpan): + Output only. Stores timing information for + pulling this build step's builder image only. + timeout (google.protobuf.duration_pb2.Duration): + Time limit for executing this build step. If + not defined, the step has no time limit and will + be allowed to continue to run until either it + completes or the build itself times out. + status (google.devtools.cloudbuild_v1.types.Build.Status): + Output only. Status of the build step. At + this time, build step status is only updated on + build completion; step status is not updated in + real-time as the build progresses. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + env = proto.RepeatedField( + proto.STRING, + number=2, + ) + args = proto.RepeatedField( + proto.STRING, + number=3, + ) + dir_ = proto.Field( + proto.STRING, + number=4, + ) + id = proto.Field( + proto.STRING, + number=5, + ) + wait_for = proto.RepeatedField( + proto.STRING, + number=6, + ) + entrypoint = proto.Field( + proto.STRING, + number=7, + ) + secret_env = proto.RepeatedField( + proto.STRING, + number=8, + ) + volumes = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='Volume', + ) + timing = proto.Field( + proto.MESSAGE, + number=10, + message='TimeSpan', + ) + pull_timing = proto.Field( + proto.MESSAGE, + number=13, + message='TimeSpan', + ) + timeout = proto.Field( + proto.MESSAGE, + number=11, + message=duration_pb2.Duration, + ) + status = proto.Field( + proto.ENUM, + number=12, + enum='Build.Status', + ) + + +class Volume(proto.Message): + r"""Volume describes a Docker container volume which is mounted + into build steps in order to persist files across build step + execution. + + Attributes: + name (str): + Name of the volume to mount. + Volume names must be unique per build step and + must be valid names for Docker volumes. Each + named volume must be used by at least two build + steps. + path (str): + Path at which to mount the volume. + Paths must be absolute and cannot conflict with + other volume paths on the same build step or + with certain reserved volume paths. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + path = proto.Field( + proto.STRING, + number=2, + ) + + +class Results(proto.Message): + r"""Artifacts created by the build pipeline. + Attributes: + images (Sequence[google.devtools.cloudbuild_v1.types.BuiltImage]): + Container images that were built as a part of + the build. + build_step_images (Sequence[str]): + List of build step digests, in the order + corresponding to build step indices. + artifact_manifest (str): + Path to the artifact manifest. Only populated + when artifacts are uploaded. + num_artifacts (int): + Number of artifacts uploaded. Only populated + when artifacts are uploaded. + build_step_outputs (Sequence[bytes]): + List of build step outputs, produced by builder images, in + the order corresponding to build step indices. + + `Cloud + Builders `__ + can produce this output by writing to + ``$BUILDER_OUTPUT/output``. Only the first 4KB of data is + stored. + artifact_timing (google.devtools.cloudbuild_v1.types.TimeSpan): + Time to push all non-container artifacts. + """ + + images = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='BuiltImage', + ) + build_step_images = proto.RepeatedField( + proto.STRING, + number=3, + ) + artifact_manifest = proto.Field( + proto.STRING, + number=4, + ) + num_artifacts = proto.Field( + proto.INT64, + number=5, + ) + build_step_outputs = proto.RepeatedField( + proto.BYTES, + number=6, + ) + artifact_timing = proto.Field( + proto.MESSAGE, + number=7, + message='TimeSpan', + ) + + +class ArtifactResult(proto.Message): + r"""An artifact that was uploaded during a build. This + is a single record in the artifact manifest JSON file. + + Attributes: + location (str): + The path of an artifact in a Google Cloud Storage bucket, + with the generation number. For example, + ``gs://mybucket/path/to/output.jar#generation``. + file_hash (Sequence[google.devtools.cloudbuild_v1.types.FileHashes]): + The file hash of the artifact. + """ + + location = proto.Field( + proto.STRING, + number=1, + ) + file_hash = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='FileHashes', + ) + + +class Build(proto.Message): + r"""A build resource in the Cloud Build API. + + At a high level, a ``Build`` describes where to find source code, + how to build it (for example, the builder image to run on the + source), and where to store the built artifacts. + + Fields can include the following variables, which will be expanded + when the build is created: + + - $PROJECT_ID: the project ID of the build. + - $PROJECT_NUMBER: the project number of the build. + - $BUILD_ID: the autogenerated ID of the build. + - $REPO_NAME: the source repository name specified by RepoSource. + - $BRANCH_NAME: the branch name specified by RepoSource. + - $TAG_NAME: the tag name specified by RepoSource. + - $REVISION_ID or $COMMIT_SHA: the commit SHA specified by + RepoSource or resolved from the specified branch or tag. + - $SHORT_SHA: first 7 characters of $REVISION_ID or $COMMIT_SHA. + + Attributes: + name (str): + Output only. The 'Build' name with format: + ``projects/{project}/locations/{location}/builds/{build}``, + where {build} is a unique identifier generated by the + service. + id (str): + Output only. Unique identifier of the build. + project_id (str): + Output only. ID of the project. + status (google.devtools.cloudbuild_v1.types.Build.Status): + Output only. Status of the build. + status_detail (str): + Output only. Customer-readable message about + the current status. + source (google.devtools.cloudbuild_v1.types.Source): + The location of the source files to build. + steps (Sequence[google.devtools.cloudbuild_v1.types.BuildStep]): + Required. The operations to be performed on + the workspace. + results (google.devtools.cloudbuild_v1.types.Results): + Output only. Results of the build. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time at which the request to + create the build was received. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time at which execution of the + build was started. + finish_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time at which execution of the build was + finished. + + The difference between finish_time and start_time is the + duration of the build's execution. + timeout (google.protobuf.duration_pb2.Duration): + Amount of time that this build should be allowed to run, to + second granularity. If this amount of time elapses, work on + the build will cease and the build status will be + ``TIMEOUT``. + + ``timeout`` starts ticking from ``startTime``. + + Default time is ten minutes. + images (Sequence[str]): + A list of images to be pushed upon the successful completion + of all build steps. + + The images are pushed using the builder service account's + credentials. + + The digests of the pushed images will be stored in the + ``Build`` resource's results field. + + If any of the images fail to be pushed, the build status is + marked ``FAILURE``. + queue_ttl (google.protobuf.duration_pb2.Duration): + TTL in queue for this build. If provided and the build is + enqueued longer than this value, the build will expire and + the build status will be ``EXPIRED``. + + The TTL starts ticking from create_time. + artifacts (google.devtools.cloudbuild_v1.types.Artifacts): + Artifacts produced by the build that should + be uploaded upon successful completion of all + build steps. + logs_bucket (str): + Google Cloud Storage bucket where logs should be written + (see `Bucket Name + Requirements `__). + Logs file names will be of the format + ``${logs_bucket}/log-${build_id}.txt``. + source_provenance (google.devtools.cloudbuild_v1.types.SourceProvenance): + Output only. A permanent fixed identifier for + source. + build_trigger_id (str): + Output only. The ID of the ``BuildTrigger`` that triggered + this build, if it was triggered automatically. + options (google.devtools.cloudbuild_v1.types.BuildOptions): + Special options for this build. + log_url (str): + Output only. URL to logs for this build in + Google Cloud Console. + substitutions (Sequence[google.devtools.cloudbuild_v1.types.Build.SubstitutionsEntry]): + Substitutions data for ``Build`` resource. + tags (Sequence[str]): + Tags for annotation of a ``Build``. These are not docker + tags. + secrets (Sequence[google.devtools.cloudbuild_v1.types.Secret]): + Secrets to decrypt using Cloud Key Management Service. Note: + Secret Manager is the recommended technique for managing + sensitive data with Cloud Build. Use ``available_secrets`` + to configure builds to access secrets from Secret Manager. + For instructions, see: + https://cloud.google.com/cloud-build/docs/securing-builds/use-secrets + timing (Sequence[google.devtools.cloudbuild_v1.types.Build.TimingEntry]): + Output only. Stores timing information for phases of the + build. Valid keys are: + + - BUILD: time to execute all build steps + - PUSH: time to push all specified images. + - FETCHSOURCE: time to fetch source. + + If the build does not specify source or images, these keys + will not be included. + service_account (str): + IAM service account whose credentials will be used at build + runtime. Must be of the format + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. ACCOUNT + can be email address or uniqueId of the service account. + available_secrets (google.devtools.cloudbuild_v1.types.Secrets): + Secrets and secret environment variables. + warnings (Sequence[google.devtools.cloudbuild_v1.types.Build.Warning]): + Output only. Non-fatal problems encountered + during the execution of the build. + failure_info (google.devtools.cloudbuild_v1.types.Build.FailureInfo): + Output only. Contains information about the + build when status=FAILURE. + """ + class Status(proto.Enum): + r"""Possible status of a build or build step.""" + STATUS_UNKNOWN = 0 + QUEUED = 1 + WORKING = 2 + SUCCESS = 3 + FAILURE = 4 + INTERNAL_ERROR = 5 + TIMEOUT = 6 + CANCELLED = 7 + EXPIRED = 9 + + class Warning(proto.Message): + r"""A non-fatal problem encountered during the execution of the + build. + + Attributes: + text (str): + Explanation of the warning generated. + priority (google.devtools.cloudbuild_v1.types.Build.Warning.Priority): + The priority for this warning. + """ + class Priority(proto.Enum): + r"""The relative importance of this warning.""" + PRIORITY_UNSPECIFIED = 0 + INFO = 1 + WARNING = 2 + ALERT = 3 + + text = proto.Field( + proto.STRING, + number=1, + ) + priority = proto.Field( + proto.ENUM, + number=2, + enum='Build.Warning.Priority', + ) + + class FailureInfo(proto.Message): + r"""A fatal problem encountered during the execution of the + build. + + Attributes: + type_ (google.devtools.cloudbuild_v1.types.Build.FailureInfo.FailureType): + The name of the failure. + detail (str): + Explains the failure issue in more detail + using hard-coded text. + """ + class FailureType(proto.Enum): + r"""The name of a fatal problem encountered during the execution + of the build. + """ + FAILURE_TYPE_UNSPECIFIED = 0 + PUSH_FAILED = 1 + PUSH_IMAGE_NOT_FOUND = 2 + PUSH_NOT_AUTHORIZED = 3 + LOGGING_FAILURE = 4 + USER_BUILD_STEP = 5 + FETCH_SOURCE_FAILED = 6 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Build.FailureInfo.FailureType', + ) + detail = proto.Field( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=45, + ) + id = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=16, + ) + status = proto.Field( + proto.ENUM, + number=2, + enum=Status, + ) + status_detail = proto.Field( + proto.STRING, + number=24, + ) + source = proto.Field( + proto.MESSAGE, + number=3, + message='Source', + ) + steps = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='BuildStep', + ) + results = proto.Field( + proto.MESSAGE, + number=10, + message='Results', + ) + create_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + start_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + finish_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + timeout = proto.Field( + proto.MESSAGE, + number=12, + message=duration_pb2.Duration, + ) + images = proto.RepeatedField( + proto.STRING, + number=13, + ) + queue_ttl = proto.Field( + proto.MESSAGE, + number=40, + message=duration_pb2.Duration, + ) + artifacts = proto.Field( + proto.MESSAGE, + number=37, + message='Artifacts', + ) + logs_bucket = proto.Field( + proto.STRING, + number=19, + ) + source_provenance = proto.Field( + proto.MESSAGE, + number=21, + message='SourceProvenance', + ) + build_trigger_id = proto.Field( + proto.STRING, + number=22, + ) + options = proto.Field( + proto.MESSAGE, + number=23, + message='BuildOptions', + ) + log_url = proto.Field( + proto.STRING, + number=25, + ) + substitutions = proto.MapField( + proto.STRING, + proto.STRING, + number=29, + ) + tags = proto.RepeatedField( + proto.STRING, + number=31, + ) + secrets = proto.RepeatedField( + proto.MESSAGE, + number=32, + message='Secret', + ) + timing = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=33, + message='TimeSpan', + ) + service_account = proto.Field( + proto.STRING, + number=42, + ) + available_secrets = proto.Field( + proto.MESSAGE, + number=47, + message='Secrets', + ) + warnings = proto.RepeatedField( + proto.MESSAGE, + number=49, + message=Warning, + ) + failure_info = proto.Field( + proto.MESSAGE, + number=51, + message=FailureInfo, + ) + + +class Artifacts(proto.Message): + r"""Artifacts produced by a build that should be uploaded upon + successful completion of all build steps. + + Attributes: + images (Sequence[str]): + A list of images to be pushed upon the + successful completion of all build steps. + + The images will be pushed using the builder + service account's credentials. + The digests of the pushed images will be stored + in the Build resource's results field. + + If any of the images fail to be pushed, the + build is marked FAILURE. + objects (google.devtools.cloudbuild_v1.types.Artifacts.ArtifactObjects): + A list of objects to be uploaded to Cloud + Storage upon successful completion of all build + steps. + Files in the workspace matching specified paths + globs will be uploaded to the specified Cloud + Storage location using the builder service + account's credentials. + + The location and generation of the uploaded + objects will be stored in the Build resource's + results field. + + If any objects fail to be pushed, the build is + marked FAILURE. + """ + + class ArtifactObjects(proto.Message): + r"""Files in the workspace to upload to Cloud Storage upon + successful completion of all build steps. + + Attributes: + location (str): + Cloud Storage bucket and optional object path, in the form + "gs://bucket/path/to/somewhere/". (see `Bucket Name + Requirements `__). + + Files in the workspace matching any path pattern will be + uploaded to Cloud Storage with this location as a prefix. + paths (Sequence[str]): + Path globs used to match files in the build's + workspace. + timing (google.devtools.cloudbuild_v1.types.TimeSpan): + Output only. Stores timing information for + pushing all artifact objects. + """ + + location = proto.Field( + proto.STRING, + number=1, + ) + paths = proto.RepeatedField( + proto.STRING, + number=2, + ) + timing = proto.Field( + proto.MESSAGE, + number=3, + message='TimeSpan', + ) + + images = proto.RepeatedField( + proto.STRING, + number=1, + ) + objects = proto.Field( + proto.MESSAGE, + number=2, + message=ArtifactObjects, + ) + + +class TimeSpan(proto.Message): + r"""Start and end times for a build execution phase. + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start of time span. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End of time span. + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class BuildOperationMetadata(proto.Message): + r"""Metadata for build operations. + Attributes: + build (google.devtools.cloudbuild_v1.types.Build): + The build that the operation is tracking. + """ + + build = proto.Field( + proto.MESSAGE, + number=1, + message='Build', + ) + + +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.devtools.cloudbuild_v1.types.StorageSource): + A copy of the build's ``source.storage_source``, if exists, + with any generations resolved. + resolved_repo_source (google.devtools.cloudbuild_v1.types.RepoSource): + A copy of the build's ``source.repo_source``, if exists, + with any revisions resolved. + resolved_storage_source_manifest (google.devtools.cloudbuild_v1.types.StorageSourceManifest): + A copy of the build's ``source.storage_source_manifest``, if + exists, with any revisions resolved. This feature is in + Preview. + file_hashes (Sequence[google.devtools.cloudbuild_v1.types.SourceProvenance.FileHashesEntry]): + Output only. Hash(es) of the build source, which can be used + to verify that the original source integrity was maintained + in the build. Note that ``FileHashes`` will only be + populated if ``BuildOptions`` has requested a + ``SourceProvenanceHash``. + + The keys to this map are file paths used as build source and + the values contain the hash values for those files. + + If the build source came in a single package such as a + gzipped tarfile (``.tar.gz``), the ``FileHash`` will be for + the single path to that file. + """ + + resolved_storage_source = proto.Field( + proto.MESSAGE, + number=3, + message='StorageSource', + ) + resolved_repo_source = proto.Field( + proto.MESSAGE, + number=6, + message='RepoSource', + ) + resolved_storage_source_manifest = proto.Field( + proto.MESSAGE, + number=9, + message='StorageSourceManifest', + ) + file_hashes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message='FileHashes', + ) + + +class FileHashes(proto.Message): + r"""Container message for hashes of byte content of files, used + in SourceProvenance messages to verify integrity of source input + to the build. + + Attributes: + file_hash (Sequence[google.devtools.cloudbuild_v1.types.Hash]): + Collection of file hashes. + """ + + file_hash = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Hash', + ) + + +class Hash(proto.Message): + r"""Container message for hash values. + Attributes: + type_ (google.devtools.cloudbuild_v1.types.Hash.HashType): + The type of hash that was performed. + value (bytes): + The hash value. + """ + class HashType(proto.Enum): + r"""Specifies the hash algorithm, if any.""" + NONE = 0 + SHA256 = 1 + MD5 = 2 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum=HashType, + ) + value = proto.Field( + proto.BYTES, + number=2, + ) + + +class Secrets(proto.Message): + r"""Secrets and secret environment variables. + Attributes: + secret_manager (Sequence[google.devtools.cloudbuild_v1.types.SecretManagerSecret]): + Secrets in Secret Manager and associated + secret environment variable. + inline (Sequence[google.devtools.cloudbuild_v1.types.InlineSecret]): + Secrets encrypted with KMS key and the + associated secret environment variable. + """ + + secret_manager = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SecretManagerSecret', + ) + inline = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='InlineSecret', + ) + + +class InlineSecret(proto.Message): + r"""Pairs a set of secret environment variables mapped to + encrypted values with the Cloud KMS key to use to decrypt the + value. + + Attributes: + kms_key_name (str): + Resource name of Cloud KMS crypto key to decrypt the + encrypted value. In format: + projects/\ */locations/*/keyRings/*/cryptoKeys/* + env_map (Sequence[google.devtools.cloudbuild_v1.types.InlineSecret.EnvMapEntry]): + Map of environment variable name to its + encrypted value. + Secret environment variables must be unique + across all of a build's secrets, and must be + used by at least one build step. Values can be + at most 64 KB in size. There can be at most 100 + secret values across all of a build's secrets. + """ + + kms_key_name = proto.Field( + proto.STRING, + number=1, + ) + env_map = proto.MapField( + proto.STRING, + proto.BYTES, + number=2, + ) + + +class SecretManagerSecret(proto.Message): + r"""Pairs a secret environment variable with a SecretVersion in + Secret Manager. + + Attributes: + version_name (str): + Resource name of the SecretVersion. In format: + projects/\ */secrets/*/versions/\* + env (str): + Environment variable name to associate with + the secret. Secret environment variables must be + unique across all of a build's secrets, and must + be used by at least one build step. + """ + + version_name = proto.Field( + proto.STRING, + number=1, + ) + env = proto.Field( + proto.STRING, + number=2, + ) + + +class Secret(proto.Message): + r"""Pairs a set of secret environment variables containing encrypted + values with the Cloud KMS key to use to decrypt the value. Note: Use + ``kmsKeyName`` with ``available_secrets`` instead of using + ``kmsKeyName`` with ``secret``. For instructions see: + https://cloud.google.com/cloud-build/docs/securing-builds/use-encrypted-credentials. + + Attributes: + kms_key_name (str): + Cloud KMS key name to use to decrypt these + envs. + secret_env (Sequence[google.devtools.cloudbuild_v1.types.Secret.SecretEnvEntry]): + Map of environment variable name to its + encrypted value. + Secret environment variables must be unique + across all of a build's secrets, and must be + used by at least one build step. Values can be + at most 64 KB in size. There can be at most 100 + secret values across all of a build's secrets. + """ + + kms_key_name = proto.Field( + proto.STRING, + number=1, + ) + secret_env = proto.MapField( + proto.STRING, + proto.BYTES, + number=3, + ) + + +class CreateBuildRequest(proto.Message): + r"""Request to create a new build. + Attributes: + parent (str): + The parent resource where this build will be created. + Format: ``projects/{project}/locations/{location}`` + project_id (str): + Required. ID of the project. + build (google.devtools.cloudbuild_v1.types.Build): + Required. Build resource to create. + """ + + parent = proto.Field( + proto.STRING, + number=4, + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + build = proto.Field( + proto.MESSAGE, + number=2, + message='Build', + ) + + +class GetBuildRequest(proto.Message): + r"""Request to get a build. + Attributes: + name (str): + The name of the ``Build`` to retrieve. Format: + ``projects/{project}/locations/{location}/builds/{build}`` + project_id (str): + Required. ID of the project. + id (str): + Required. ID of the build. + """ + + name = proto.Field( + proto.STRING, + number=4, + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + + +class ListBuildsRequest(proto.Message): + r"""Request to list builds. + Attributes: + parent (str): + The parent of the collection of ``Builds``. Format: + ``projects/{project}/locations/location`` + project_id (str): + Required. ID of the project. + page_size (int): + Number of results to return in the list. + page_token (str): + The page token for the next page of Builds. + + If unspecified, the first page of results is returned. + + If the token is rejected for any reason, INVALID_ARGUMENT + will be thrown. In this case, the token should be discarded, + and pagination should be restarted from the first page of + results. + + See https://google.aip.dev/158 for more. + filter (str): + The raw filter text to constrain the results. + """ + + parent = proto.Field( + proto.STRING, + number=9, + ) + project_id = 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=8, + ) + + +class ListBuildsResponse(proto.Message): + r"""Response including listed builds. + Attributes: + builds (Sequence[google.devtools.cloudbuild_v1.types.Build]): + Builds will be sorted by ``create_time``, descending. + next_page_token (str): + Token to receive the next page of results. + This will be absent if the end of the response + list has been reached. + """ + + @property + def raw_page(self): + return self + + builds = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Build', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CancelBuildRequest(proto.Message): + r"""Request to cancel an ongoing build. + Attributes: + name (str): + The name of the ``Build`` to cancel. Format: + ``projects/{project}/locations/{location}/builds/{build}`` + project_id (str): + Required. ID of the project. + id (str): + Required. ID of the build. + """ + + name = proto.Field( + proto.STRING, + number=4, + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + + +class BuildTrigger(proto.Message): + r"""Configuration for an automated build in response to source + repository changes. + + Attributes: + resource_name (str): + The ``Trigger`` name with format: + ``projects/{project}/locations/{location}/triggers/{trigger}``, + where {trigger} is a unique identifier generated by the + service. + id (str): + Output only. Unique identifier of the + trigger. + description (str): + Human-readable description of this trigger. + name (str): + User-assigned name of the trigger. Must be + unique within the project. Trigger names must + meet the following requirements: + + They must contain only alphanumeric characters + and dashes. + They can be 1-64 characters long. + + They must begin and end with an alphanumeric + character. + tags (Sequence[str]): + Tags for annotation of a ``BuildTrigger`` + trigger_template (google.devtools.cloudbuild_v1.types.RepoSource): + Template describing the types of source changes to trigger a + build. + + Branch and tag names in trigger templates are interpreted as + regular expressions. Any branch or tag change that matches + that regular expression will trigger a build. + + Mutually exclusive with ``github``. + github (google.devtools.cloudbuild_v1.types.GitHubEventsConfig): + GitHubEventsConfig describes the configuration of a trigger + that creates a build whenever a GitHub event is received. + + Mutually exclusive with ``trigger_template``. + pubsub_config (google.devtools.cloudbuild_v1.types.PubsubConfig): + PubsubConfig describes the configuration of a + trigger that creates a build whenever a Pub/Sub + message is published. + webhook_config (google.devtools.cloudbuild_v1.types.WebhookConfig): + WebhookConfig describes the configuration of + a trigger that creates a build whenever a + webhook is sent to a trigger's webhook URL. + autodetect (bool): + Autodetect build configuration. The + following precedence is used (case insensitive): + 1. cloudbuild.yaml + 2. cloudbuild.yml + 3. cloudbuild.json + 4. Dockerfile + + Currently only available for GitHub App + Triggers. + build (google.devtools.cloudbuild_v1.types.Build): + Contents of the build template. + filename (str): + Path, from the source root, to the build + configuration file (i.e. cloudbuild.yaml). + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the trigger was + created. + disabled (bool): + If true, the trigger will never automatically + execute a build. + substitutions (Sequence[google.devtools.cloudbuild_v1.types.BuildTrigger.SubstitutionsEntry]): + Substitutions for Build resource. The keys must match the + following regular expression: ``^_[A-Z0-9_]+$``. + ignored_files (Sequence[str]): + ignored_files and included_files are file glob matches using + https://golang.org/pkg/path/filepath/#Match extended with + support for "**". + + If ignored_files and changed files are both empty, then they + are not used to determine whether or not to trigger a build. + + If ignored_files is not empty, then we ignore any files that + match any of the ignored_file globs. If the change has no + files that are outside of the ignored_files globs, then we + do not trigger a build. + included_files (Sequence[str]): + If any of the files altered in the commit pass the + ignored_files filter and included_files is empty, then as + far as this filter is concerned, we should trigger the + build. + + If any of the files altered in the commit pass the + ignored_files filter and included_files is not empty, then + we make sure that at least one of those files matches a + included_files glob. If not, then we do not trigger a build. + filter (str): + Optional. A Common Expression Language + string. + """ + + resource_name = proto.Field( + proto.STRING, + number=34, + ) + id = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=10, + ) + name = proto.Field( + proto.STRING, + number=21, + ) + tags = proto.RepeatedField( + proto.STRING, + number=19, + ) + trigger_template = proto.Field( + proto.MESSAGE, + number=7, + message='RepoSource', + ) + github = proto.Field( + proto.MESSAGE, + number=13, + message='GitHubEventsConfig', + ) + pubsub_config = proto.Field( + proto.MESSAGE, + number=29, + message='PubsubConfig', + ) + webhook_config = proto.Field( + proto.MESSAGE, + number=31, + message='WebhookConfig', + ) + autodetect = proto.Field( + proto.BOOL, + number=18, + oneof='build_template', + ) + build = proto.Field( + proto.MESSAGE, + number=4, + oneof='build_template', + message='Build', + ) + filename = proto.Field( + proto.STRING, + number=8, + oneof='build_template', + ) + create_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + disabled = proto.Field( + proto.BOOL, + number=9, + ) + substitutions = proto.MapField( + proto.STRING, + proto.STRING, + number=11, + ) + ignored_files = proto.RepeatedField( + proto.STRING, + number=15, + ) + included_files = proto.RepeatedField( + proto.STRING, + number=16, + ) + filter = proto.Field( + proto.STRING, + number=30, + ) + + +class GitHubEventsConfig(proto.Message): + r"""GitHubEventsConfig describes the configuration of a trigger + that creates a build whenever a GitHub event is received. + This message is experimental. + + Attributes: + installation_id (int): + The installationID that emits the GitHub + event. + owner (str): + Owner of the repository. For example: The + owner for + https://github.com/googlecloudplatform/cloud- + builders is "googlecloudplatform". + name (str): + Name of the repository. For example: The name + for + https://github.com/googlecloudplatform/cloud- + builders is "cloud-builders". + pull_request (google.devtools.cloudbuild_v1.types.PullRequestFilter): + filter to match changes in pull requests. + push (google.devtools.cloudbuild_v1.types.PushFilter): + filter to match changes in refs like + branches, tags. + """ + + installation_id = proto.Field( + proto.INT64, + number=1, + ) + owner = proto.Field( + proto.STRING, + number=6, + ) + name = proto.Field( + proto.STRING, + number=7, + ) + pull_request = proto.Field( + proto.MESSAGE, + number=4, + oneof='event', + message='PullRequestFilter', + ) + push = proto.Field( + proto.MESSAGE, + number=5, + oneof='event', + message='PushFilter', + ) + + +class PubsubConfig(proto.Message): + r"""PubsubConfig describes the configuration of a trigger that + creates a build whenever a Pub/Sub message is published. + + Attributes: + subscription (str): + Output only. Name of the subscription. Format is + ``projects/{project}/subscriptions/{subscription}``. + topic (str): + The name of the topic from which this subscription is + receiving messages. Format is + ``projects/{project}/topics/{topic}``. + service_account_email (str): + Service account that will make the push + request. + state (google.devtools.cloudbuild_v1.types.PubsubConfig.State): + Potential issues with the underlying Pub/Sub + subscription configuration. Only populated on + get requests. + """ + class State(proto.Enum): + r"""Enumerates potential issues with the underlying Pub/Sub + subscription configuration. + """ + STATE_UNSPECIFIED = 0 + OK = 1 + SUBSCRIPTION_DELETED = 2 + TOPIC_DELETED = 3 + SUBSCRIPTION_MISCONFIGURED = 4 + + subscription = proto.Field( + proto.STRING, + number=1, + ) + topic = proto.Field( + proto.STRING, + number=2, + ) + service_account_email = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + + +class WebhookConfig(proto.Message): + r"""WebhookConfig describes the configuration of a trigger that + creates a build whenever a webhook is sent to a trigger's + webhook URL. + + Attributes: + secret (str): + Required. Resource name for the secret + required as a URL parameter. + state (google.devtools.cloudbuild_v1.types.WebhookConfig.State): + Potential issues with the underlying Pub/Sub + subscription configuration. Only populated on + get requests. + """ + class State(proto.Enum): + r"""Enumerates potential issues with the Secret Manager secret + provided by the user. + """ + STATE_UNSPECIFIED = 0 + OK = 1 + SECRET_DELETED = 2 + + secret = proto.Field( + proto.STRING, + number=3, + oneof='auth_method', + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + + +class PullRequestFilter(proto.Message): + r"""PullRequestFilter contains filter properties for matching + GitHub Pull Requests. + + Attributes: + branch (str): + Regex of branches to match. + The syntax of the regular expressions accepted + is the syntax accepted by RE2 and described at + https://github.com/google/re2/wiki/Syntax + comment_control (google.devtools.cloudbuild_v1.types.PullRequestFilter.CommentControl): + Configure builds to run whether a repository owner or + collaborator need to comment ``/gcbrun``. + invert_regex (bool): + If true, branches that do NOT match the git_ref will trigger + a build. + """ + class CommentControl(proto.Enum): + r"""Controls behavior of Pull Request comments.""" + COMMENTS_DISABLED = 0 + COMMENTS_ENABLED = 1 + COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY = 2 + + branch = proto.Field( + proto.STRING, + number=2, + oneof='git_ref', + ) + comment_control = proto.Field( + proto.ENUM, + number=5, + enum=CommentControl, + ) + invert_regex = proto.Field( + proto.BOOL, + number=6, + ) + + +class PushFilter(proto.Message): + r"""Push contains filter properties for matching GitHub git + pushes. + + Attributes: + branch (str): + Regexes 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 + tag (str): + Regexes 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 + invert_regex (bool): + When true, only trigger a build if the revision regex does + NOT match the git_ref regex. + """ + + branch = proto.Field( + proto.STRING, + number=2, + oneof='git_ref', + ) + tag = proto.Field( + proto.STRING, + number=3, + oneof='git_ref', + ) + invert_regex = proto.Field( + proto.BOOL, + number=4, + ) + + +class CreateBuildTriggerRequest(proto.Message): + r"""Request to create a new ``BuildTrigger``. + Attributes: + parent (str): + The parent resource where this trigger will be created. + Format: ``projects/{project}/locations/{location}`` + project_id (str): + Required. ID of the project for which to + configure automatic builds. + trigger (google.devtools.cloudbuild_v1.types.BuildTrigger): + Required. ``BuildTrigger`` to create. + """ + + parent = proto.Field( + proto.STRING, + number=3, + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + trigger = proto.Field( + proto.MESSAGE, + number=2, + message='BuildTrigger', + ) + + +class GetBuildTriggerRequest(proto.Message): + r"""Returns the ``BuildTrigger`` with the specified ID. + Attributes: + name (str): + The name of the ``Trigger`` to retrieve. Format: + ``projects/{project}/locations/{location}/triggers/{trigger}`` + project_id (str): + Required. ID of the project that owns the + trigger. + trigger_id (str): + Required. Identifier (``id`` or ``name``) of the + ``BuildTrigger`` to get. + """ + + name = proto.Field( + proto.STRING, + number=3, + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + trigger_id = proto.Field( + proto.STRING, + number=2, + ) + + +class ListBuildTriggersRequest(proto.Message): + r"""Request to list existing ``BuildTriggers``. + Attributes: + parent (str): + The parent of the collection of ``Triggers``. Format: + ``projects/{project}/locations/{location}`` + project_id (str): + Required. ID of the project for which to list + BuildTriggers. + page_size (int): + Number of results to return in the list. + page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + parent = proto.Field( + proto.STRING, + number=4, + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListBuildTriggersResponse(proto.Message): + r"""Response containing existing ``BuildTriggers``. + Attributes: + triggers (Sequence[google.devtools.cloudbuild_v1.types.BuildTrigger]): + ``BuildTriggers`` for the project, sorted by ``create_time`` + descending. + next_page_token (str): + Token to receive the next page of results. + """ + + @property + def raw_page(self): + return self + + triggers = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='BuildTrigger', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteBuildTriggerRequest(proto.Message): + r"""Request to delete a ``BuildTrigger``. + Attributes: + name (str): + The name of the ``Trigger`` to delete. Format: + ``projects/{project}/locations/{location}/triggers/{trigger}`` + project_id (str): + Required. ID of the project that owns the + trigger. + trigger_id (str): + Required. ID of the ``BuildTrigger`` to delete. + """ + + name = proto.Field( + proto.STRING, + number=3, + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + trigger_id = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateBuildTriggerRequest(proto.Message): + r"""Request to update an existing ``BuildTrigger``. + Attributes: + project_id (str): + Required. ID of the project that owns the + trigger. + trigger_id (str): + Required. ID of the ``BuildTrigger`` to update. + trigger (google.devtools.cloudbuild_v1.types.BuildTrigger): + Required. ``BuildTrigger`` to update. + """ + + project_id = proto.Field( + proto.STRING, + number=1, + ) + trigger_id = proto.Field( + proto.STRING, + number=2, + ) + trigger = proto.Field( + proto.MESSAGE, + number=3, + message='BuildTrigger', + ) + + +class BuildOptions(proto.Message): + r"""Optional arguments to enable specific features of builds. + Attributes: + source_provenance_hash (Sequence[google.devtools.cloudbuild_v1.types.Hash.HashType]): + Requested hash for SourceProvenance. + requested_verify_option (google.devtools.cloudbuild_v1.types.BuildOptions.VerifyOption): + Requested verifiability options. + machine_type (google.devtools.cloudbuild_v1.types.BuildOptions.MachineType): + Compute Engine machine type on which to run + the build. + disk_size_gb (int): + Requested disk size for the VM that runs the build. Note + that this is *NOT* "disk free"; some of the space will be + used by the operating system and build utilities. Also note + that this is the minimum disk size that will be allocated + for the build -- the build may run with a larger disk than + requested. At present, the maximum disk size is 1000GB; + builds that request more than the maximum are rejected with + an error. + substitution_option (google.devtools.cloudbuild_v1.types.BuildOptions.SubstitutionOption): + Option to specify behavior when there is an error in the + substitution checks. + + NOTE: this is always set to ALLOW_LOOSE for triggered builds + and cannot be overridden in the build configuration file. + dynamic_substitutions (bool): + Option to specify whether or not to apply + bash style string operations to the + substitutions. + NOTE: this is always enabled for triggered + builds and cannot be overridden in the build + configuration file. + log_streaming_option (google.devtools.cloudbuild_v1.types.BuildOptions.LogStreamingOption): + Option to define build log streaming behavior + to Google Cloud Storage. + worker_pool (str): + This field deprecated; please use ``pool.name`` instead. + pool (google.devtools.cloudbuild_v1.types.BuildOptions.PoolOption): + Optional. Specification for execution on a ``WorkerPool``. + + See `running builds in a private + pool `__ + for more information. + logging (google.devtools.cloudbuild_v1.types.BuildOptions.LoggingMode): + Option to specify the logging mode, which + determines if and where build logs are stored. + env (Sequence[str]): + A list of global environment variable + definitions that will exist for all build steps + in this build. If a variable is defined in both + globally and in a build step, the variable will + use the build step value. + The elements are of the form "KEY=VALUE" for the + environment variable "KEY" being given the value + "VALUE". + secret_env (Sequence[str]): + A list of global environment variables, which are encrypted + using a Cloud Key Management Service crypto key. These + values must be specified in the build's ``Secret``. These + variables will be available to all build steps in this + build. + volumes (Sequence[google.devtools.cloudbuild_v1.types.Volume]): + Global list of volumes to mount for ALL build + steps + Each volume is created as an empty volume prior + to starting the build process. Upon completion + of the build, volumes and their contents are + discarded. Global volume names and paths cannot + conflict with the volumes defined a build step. + + Using a global volume in a build with only one + step is not valid as it is indicative of a build + request with an incorrect configuration. + """ + class VerifyOption(proto.Enum): + r"""Specifies the manner in which the build should be verified, + if at all. + """ + NOT_VERIFIED = 0 + VERIFIED = 1 + + class MachineType(proto.Enum): + r"""Supported Compute Engine machine types. For more information, see + `Machine + types `__. + """ + UNSPECIFIED = 0 + N1_HIGHCPU_8 = 1 + N1_HIGHCPU_32 = 2 + E2_HIGHCPU_8 = 5 + E2_HIGHCPU_32 = 6 + + class SubstitutionOption(proto.Enum): + r"""Specifies the behavior when there is an error in the + substitution checks. + """ + MUST_MATCH = 0 + ALLOW_LOOSE = 1 + + class LogStreamingOption(proto.Enum): + r"""Specifies the behavior when writing build logs to Google + Cloud Storage. + """ + STREAM_DEFAULT = 0 + STREAM_ON = 1 + STREAM_OFF = 2 + + class LoggingMode(proto.Enum): + r"""Specifies the logging mode.""" + LOGGING_UNSPECIFIED = 0 + LEGACY = 1 + GCS_ONLY = 2 + STACKDRIVER_ONLY = 3 + CLOUD_LOGGING_ONLY = 5 + NONE = 4 + + class PoolOption(proto.Message): + r"""Details about how a build should be executed on a ``WorkerPool``. + + See `running builds in a private + pool `__ + for more information. + + Attributes: + name (str): + The ``WorkerPool`` resource to execute the build on. You + must have ``cloudbuild.workerpools.use`` on the project + hosting the WorkerPool. + + Format + projects/{project}/locations/{location}/workerPools/{workerPoolId} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + source_provenance_hash = proto.RepeatedField( + proto.ENUM, + number=1, + enum='Hash.HashType', + ) + requested_verify_option = proto.Field( + proto.ENUM, + number=2, + enum=VerifyOption, + ) + machine_type = proto.Field( + proto.ENUM, + number=3, + enum=MachineType, + ) + disk_size_gb = proto.Field( + proto.INT64, + number=6, + ) + substitution_option = proto.Field( + proto.ENUM, + number=4, + enum=SubstitutionOption, + ) + dynamic_substitutions = proto.Field( + proto.BOOL, + number=17, + ) + log_streaming_option = proto.Field( + proto.ENUM, + number=5, + enum=LogStreamingOption, + ) + worker_pool = proto.Field( + proto.STRING, + number=7, + ) + pool = proto.Field( + proto.MESSAGE, + number=19, + message=PoolOption, + ) + logging = proto.Field( + proto.ENUM, + number=11, + enum=LoggingMode, + ) + env = proto.RepeatedField( + proto.STRING, + number=12, + ) + secret_env = proto.RepeatedField( + proto.STRING, + number=13, + ) + volumes = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='Volume', + ) + + +class ReceiveTriggerWebhookRequest(proto.Message): + r"""ReceiveTriggerWebhookRequest [Experimental] is the request object + accepted by the ReceiveTriggerWebhook method. + + Attributes: + name (str): + The name of the ``ReceiveTriggerWebhook`` to retrieve. + Format: + ``projects/{project}/locations/{location}/triggers/{trigger}`` + body (google.api.httpbody_pb2.HttpBody): + HTTP request body. + project_id (str): + Project in which the specified trigger lives + trigger (str): + Name of the trigger to run the payload + against + secret (str): + Secret token used for authorization if an + OAuth token isn't provided. + """ + + name = proto.Field( + proto.STRING, + number=5, + ) + body = proto.Field( + proto.MESSAGE, + number=1, + message=httpbody_pb2.HttpBody, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + trigger = proto.Field( + proto.STRING, + number=3, + ) + secret = proto.Field( + proto.STRING, + number=4, + ) + + +class ReceiveTriggerWebhookResponse(proto.Message): + r"""ReceiveTriggerWebhookResponse [Experimental] is the response object + for the ReceiveTriggerWebhook method. + """ + + +class WorkerPool(proto.Message): + r"""Configuration for a ``WorkerPool``. + + Cloud Build owns and maintains a pool of workers for general use and + have no access to a project's private network. By default, builds + submitted to Cloud Build will use a worker from this pool. + + If your build needs access to resources on a private network, create + and use a ``WorkerPool`` to run your builds. Private + ``WorkerPool``\ s give your builds access to any single VPC network + that you administer, including any on-prem resources connected to + that VPC network. For an overview of private pools, see `Private + pools + overview `__. + + Attributes: + name (str): + Output only. The resource name of the ``WorkerPool``, with + format + ``projects/{project}/locations/{location}/workerPools/{worker_pool}``. + The value of ``{worker_pool}`` is provided by + ``worker_pool_id`` in ``CreateWorkerPool`` request and the + value of ``{location}`` is determined by the endpoint + accessed. + display_name (str): + A user-specified, human-readable name for the + ``WorkerPool``. If provided, this value must be 1-63 + characters. + uid (str): + Output only. A unique identifier for the ``WorkerPool``. + annotations (Sequence[google.devtools.cloudbuild_v1.types.WorkerPool.AnnotationsEntry]): + User specified annotations. See + https://google.aip.dev/128#annotations for more + details such as format and size limitations. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time at which the request to create the + ``WorkerPool`` was received. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time at which the request to update the + ``WorkerPool`` was received. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time at which the request to delete the + ``WorkerPool`` was received. + state (google.devtools.cloudbuild_v1.types.WorkerPool.State): + Output only. ``WorkerPool`` state. + private_pool_v1_config (google.devtools.cloudbuild_v1.types.PrivatePoolV1Config): + Private Pool using a v1 configuration. + etag (str): + Output only. Checksum computed by the server. + May be sent on update and delete requests to + ensure that the client has an up-to-date value + before proceeding. + """ + class State(proto.Enum): + r"""State of the ``WorkerPool``.""" + STATE_UNSPECIFIED = 0 + CREATING = 1 + RUNNING = 2 + DELETING = 3 + DELETED = 4 + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + uid = proto.Field( + proto.STRING, + number=3, + ) + annotations = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + create_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + delete_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + state = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + private_pool_v1_config = proto.Field( + proto.MESSAGE, + number=12, + oneof='config', + message='PrivatePoolV1Config', + ) + etag = proto.Field( + proto.STRING, + number=11, + ) + + +class PrivatePoolV1Config(proto.Message): + r"""Configuration for a V1 ``PrivatePool``. + Attributes: + worker_config (google.devtools.cloudbuild_v1.types.PrivatePoolV1Config.WorkerConfig): + Machine configuration for the workers in the + pool. + network_config (google.devtools.cloudbuild_v1.types.PrivatePoolV1Config.NetworkConfig): + Network configuration for the pool. + """ + + class WorkerConfig(proto.Message): + r"""Defines the configuration to be used for creating workers in + the pool. + + Attributes: + machine_type (str): + Machine type of a worker, such as ``e2-medium``. See `Worker + pool config + file `__. + If left blank, Cloud Build will use a sensible default. + disk_size_gb (int): + Size of the disk attached to the worker, in GB. See `Worker + pool config + file `__. + Specify a value of up to 1000. If ``0`` is specified, Cloud + Build will use a standard disk size. + """ + + machine_type = proto.Field( + proto.STRING, + number=1, + ) + disk_size_gb = proto.Field( + proto.INT64, + number=2, + ) + + class NetworkConfig(proto.Message): + r"""Defines the network configuration for the pool. + Attributes: + peered_network (str): + Required. Immutable. The network definition that the workers + are peered to. If this section is left empty, the workers + will be peered to ``WorkerPool.project_id`` on the service + producer network. Must be in the format + ``projects/{project}/global/networks/{network}``, where + ``{project}`` is a project number, such as ``12345``, and + ``{network}`` is the name of a VPC network in the project. + See `Understanding network configuration + options `__ + egress_option (google.devtools.cloudbuild_v1.types.PrivatePoolV1Config.NetworkConfig.EgressOption): + Option to configure network egress for the + workers. + """ + class EgressOption(proto.Enum): + r"""Defines the egress option for the pool.""" + EGRESS_OPTION_UNSPECIFIED = 0 + NO_PUBLIC_EGRESS = 1 + PUBLIC_EGRESS = 2 + + peered_network = proto.Field( + proto.STRING, + number=1, + ) + egress_option = proto.Field( + proto.ENUM, + number=2, + enum='PrivatePoolV1Config.NetworkConfig.EgressOption', + ) + + worker_config = proto.Field( + proto.MESSAGE, + number=1, + message=WorkerConfig, + ) + network_config = proto.Field( + proto.MESSAGE, + number=2, + message=NetworkConfig, + ) + + +class CreateWorkerPoolRequest(proto.Message): + r"""Request to create a new ``WorkerPool``. + Attributes: + parent (str): + Required. The parent resource where this worker pool will be + created. Format: + ``projects/{project}/locations/{location}``. + worker_pool (google.devtools.cloudbuild_v1.types.WorkerPool): + Required. ``WorkerPool`` resource to create. + worker_pool_id (str): + Required. Immutable. The ID to use for the ``WorkerPool``, + which will become the final component of the resource name. + + This value should be 1-63 characters, and valid characters + are /[a-z][0-9]-/. + validate_only (bool): + If set, validate the request and preview the + response, but do not actually post it. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + worker_pool = proto.Field( + proto.MESSAGE, + number=2, + message='WorkerPool', + ) + worker_pool_id = proto.Field( + proto.STRING, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetWorkerPoolRequest(proto.Message): + r"""Request to get a ``WorkerPool`` with the specified name. + Attributes: + name (str): + Required. The name of the ``WorkerPool`` to retrieve. + Format: + ``projects/{project}/locations/{location}/workerPools/{workerPool}``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteWorkerPoolRequest(proto.Message): + r"""Request to delete a ``WorkerPool``. + Attributes: + name (str): + Required. The name of the ``WorkerPool`` to delete. Format: + ``projects/{project}/locations/{workerPool}/workerPools/{workerPool}``. + etag (str): + Optional. If this is provided, it must match + the server's etag on the workerpool for the + request to be processed. + allow_missing (bool): + If set to true, and the ``WorkerPool`` is not found, the + request will succeed but no action will be taken on the + server. + validate_only (bool): + If set, validate the request and preview the + response, but do not actually post it. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + etag = proto.Field( + proto.STRING, + number=2, + ) + allow_missing = proto.Field( + proto.BOOL, + number=3, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkerPoolRequest(proto.Message): + r"""Request to update a ``WorkerPool``. + Attributes: + worker_pool (google.devtools.cloudbuild_v1.types.WorkerPool): + Required. The ``WorkerPool`` to update. + + The ``name`` field is used to identify the ``WorkerPool`` to + update. Format: + ``projects/{project}/locations/{location}/workerPools/{workerPool}``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + A mask specifying which fields in ``worker_pool`` to update. + validate_only (bool): + If set, validate the request and preview the + response, but do not actually post it. + """ + + worker_pool = proto.Field( + proto.MESSAGE, + number=1, + message='WorkerPool', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListWorkerPoolsRequest(proto.Message): + r"""Request to list ``WorkerPool``\ s. + Attributes: + parent (str): + Required. The parent of the collection of ``WorkerPools``. + Format: ``projects/{project}/locations/{location}``. + page_size (int): + The maximum number of ``WorkerPool``\ s to return. The + service may return fewer than this value. If omitted, the + server will use a sensible default. + page_token (str): + A page token, received from a previous ``ListWorkerPools`` + call. Provide this to retrieve the subsequent page. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListWorkerPoolsResponse(proto.Message): + r"""Response containing existing ``WorkerPools``. + Attributes: + worker_pools (Sequence[google.devtools.cloudbuild_v1.types.WorkerPool]): + ``WorkerPools`` for the specified project. + next_page_token (str): + Continuation token used to page through large + result sets. Provide this value in a subsequent + ListWorkerPoolsRequest to return the next page + of results. + """ + + @property + def raw_page(self): + return self + + worker_pools = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkerPool', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateWorkerPoolOperationMetadata(proto.Message): + r"""Metadata for the ``CreateWorkerPool`` operation. + Attributes: + worker_pool (str): + The resource name of the ``WorkerPool`` to create. Format: + ``projects/{project}/locations/{location}/workerPools/{worker_pool}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Time the operation was created. + complete_time (google.protobuf.timestamp_pb2.Timestamp): + Time the operation was completed. + """ + + worker_pool = proto.Field( + proto.STRING, + number=1, + ) + create_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + complete_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class UpdateWorkerPoolOperationMetadata(proto.Message): + r"""Metadata for the ``UpdateWorkerPool`` operation. + Attributes: + worker_pool (str): + The resource name of the ``WorkerPool`` being updated. + Format: + ``projects/{project}/locations/{location}/workerPools/{worker_pool}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Time the operation was created. + complete_time (google.protobuf.timestamp_pb2.Timestamp): + Time the operation was completed. + """ + + worker_pool = proto.Field( + proto.STRING, + number=1, + ) + create_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + complete_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteWorkerPoolOperationMetadata(proto.Message): + r"""Metadata for the ``DeleteWorkerPool`` operation. + Attributes: + worker_pool (str): + The resource name of the ``WorkerPool`` being deleted. + Format: + ``projects/{project}/locations/{location}/workerPools/{worker_pool}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Time the operation was created. + complete_time (google.protobuf.timestamp_pb2.Timestamp): + Time the operation was completed. + """ + + worker_pool = proto.Field( + proto.STRING, + number=1, + ) + create_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + complete_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 00000000..213c014a --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/devtools/cloudbuild_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1/scripts/fixup_cloudbuild_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_cloudbuild_v1_keywords.py new file mode 100644 index 00000000..99a089f1 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_cloudbuild_v1_keywords.py @@ -0,0 +1,192 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class cloudbuildCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'cancel_build': ('project_id', 'id', 'name', ), + 'create_build': ('project_id', 'build', 'parent', ), + 'create_build_trigger': ('project_id', 'trigger', 'parent', ), + 'create_worker_pool': ('parent', 'worker_pool', 'worker_pool_id', 'validate_only', ), + 'delete_build_trigger': ('project_id', 'trigger_id', 'name', ), + 'delete_worker_pool': ('name', 'etag', 'allow_missing', 'validate_only', ), + 'get_build': ('project_id', 'id', 'name', ), + 'get_build_trigger': ('project_id', 'trigger_id', 'name', ), + 'get_worker_pool': ('name', ), + 'list_builds': ('project_id', 'parent', 'page_size', 'page_token', 'filter', ), + 'list_build_triggers': ('project_id', 'parent', 'page_size', 'page_token', ), + 'list_worker_pools': ('parent', 'page_size', 'page_token', ), + 'receive_trigger_webhook': ('name', 'body', 'project_id', 'trigger', 'secret', ), + 'retry_build': ('project_id', 'id', 'name', ), + 'run_build_trigger': ('project_id', 'trigger_id', 'name', 'source', ), + 'update_build_trigger': ('project_id', 'trigger_id', 'trigger', ), + 'update_worker_pool': ('worker_pool', 'update_mask', 'validate_only', ), + } + + 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: not a.keyword.value 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=cloudbuildCallTransformer(), +): + """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 cloudbuild client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 00000000..5450e820 --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-devtools-cloudbuild', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.devtools'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py b/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py new file mode 100644 index 00000000..029c0ef3 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py @@ -0,0 +1,5062 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.devtools.cloudbuild_v1.services.cloud_build import CloudBuildAsyncClient +from google.devtools.cloudbuild_v1.services.cloud_build import CloudBuildClient +from google.devtools.cloudbuild_v1.services.cloud_build import pagers +from google.devtools.cloudbuild_v1.services.cloud_build import transports +from google.devtools.cloudbuild_v1.services.cloud_build.transports.base import _GOOGLE_AUTH_VERSION +from google.devtools.cloudbuild_v1.types import cloudbuild +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CloudBuildClient._get_default_mtls_endpoint(None) is None + assert CloudBuildClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CloudBuildClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CloudBuildClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CloudBuildClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CloudBuildClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + CloudBuildClient, + CloudBuildAsyncClient, +]) +def test_cloud_build_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudbuild.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CloudBuildGrpcTransport, "grpc"), + (transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_cloud_build_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", [ + CloudBuildClient, + CloudBuildAsyncClient, +]) +def test_cloud_build_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudbuild.googleapis.com:443' + + +def test_cloud_build_client_get_transport_class(): + transport = CloudBuildClient.get_transport_class() + available_transports = [ + transports.CloudBuildGrpcTransport, + ] + assert transport in available_transports + + transport = CloudBuildClient.get_transport_class("grpc") + assert transport == transports.CloudBuildGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CloudBuildClient, transports.CloudBuildGrpcTransport, "grpc"), + (CloudBuildAsyncClient, transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CloudBuildClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudBuildClient)) +@mock.patch.object(CloudBuildAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudBuildAsyncClient)) +def test_cloud_build_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(CloudBuildClient, '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(CloudBuildClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CloudBuildClient, transports.CloudBuildGrpcTransport, "grpc", "true"), + (CloudBuildAsyncClient, transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CloudBuildClient, transports.CloudBuildGrpcTransport, "grpc", "false"), + (CloudBuildAsyncClient, transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CloudBuildClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudBuildClient)) +@mock.patch.object(CloudBuildAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudBuildAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_build_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CloudBuildClient, transports.CloudBuildGrpcTransport, "grpc"), + (CloudBuildAsyncClient, transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_cloud_build_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CloudBuildClient, transports.CloudBuildGrpcTransport, "grpc"), + (CloudBuildAsyncClient, transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_cloud_build_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_cloud_build_client_client_options_from_dict(): + with mock.patch('google.devtools.cloudbuild_v1.services.cloud_build.transports.CloudBuildGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CloudBuildClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_create_build(transport: str = 'grpc', request_type=cloudbuild.CreateBuildRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_build(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CreateBuildRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_build_from_dict(): + test_create_build(request_type=dict) + + +def test_create_build_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 = CloudBuildClient( + 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_build), + '__call__') as call: + client.create_build() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CreateBuildRequest() + + +@pytest.mark.asyncio +async def test_create_build_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.CreateBuildRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build), + '__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_build(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CreateBuildRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_build_async_from_dict(): + await test_create_build_async(request_type=dict) + + +def test_create_build_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_build), + '__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_build( + project_id='project_id_value', + build=cloudbuild.Build(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].build == cloudbuild.Build(name='name_value') + + +def test_create_build_flattened_error(): + client = CloudBuildClient( + 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_build( + cloudbuild.CreateBuildRequest(), + project_id='project_id_value', + build=cloudbuild.Build(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_build_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_build), + '__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_build( + project_id='project_id_value', + build=cloudbuild.Build(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].build == cloudbuild.Build(name='name_value') + + +@pytest.mark.asyncio +async def test_create_build_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_build( + cloudbuild.CreateBuildRequest(), + project_id='project_id_value', + build=cloudbuild.Build(name='name_value'), + ) + + +def test_get_build(transport: str = 'grpc', request_type=cloudbuild.GetBuildRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.Build( + name='name_value', + id='id_value', + project_id='project_id_value', + status=cloudbuild.Build.Status.QUEUED, + status_detail='status_detail_value', + images=['images_value'], + logs_bucket='logs_bucket_value', + build_trigger_id='build_trigger_id_value', + log_url='log_url_value', + tags=['tags_value'], + service_account='service_account_value', + ) + response = client.get_build(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.GetBuildRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.Build) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.project_id == 'project_id_value' + assert response.status == cloudbuild.Build.Status.QUEUED + assert response.status_detail == 'status_detail_value' + assert response.images == ['images_value'] + assert response.logs_bucket == 'logs_bucket_value' + assert response.build_trigger_id == 'build_trigger_id_value' + assert response.log_url == 'log_url_value' + assert response.tags == ['tags_value'] + assert response.service_account == 'service_account_value' + + +def test_get_build_from_dict(): + test_get_build(request_type=dict) + + +def test_get_build_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 = CloudBuildClient( + 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_build), + '__call__') as call: + client.get_build() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.GetBuildRequest() + + +@pytest.mark.asyncio +async def test_get_build_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.GetBuildRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.Build( + name='name_value', + id='id_value', + project_id='project_id_value', + status=cloudbuild.Build.Status.QUEUED, + status_detail='status_detail_value', + images=['images_value'], + logs_bucket='logs_bucket_value', + build_trigger_id='build_trigger_id_value', + log_url='log_url_value', + tags=['tags_value'], + service_account='service_account_value', + )) + response = await client.get_build(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.GetBuildRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.Build) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.project_id == 'project_id_value' + assert response.status == cloudbuild.Build.Status.QUEUED + assert response.status_detail == 'status_detail_value' + assert response.images == ['images_value'] + assert response.logs_bucket == 'logs_bucket_value' + assert response.build_trigger_id == 'build_trigger_id_value' + assert response.log_url == 'log_url_value' + assert response.tags == ['tags_value'] + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_get_build_async_from_dict(): + await test_get_build_async(request_type=dict) + + +def test_get_build_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_build), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.Build() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_build( + project_id='project_id_value', + id='id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].id == 'id_value' + + +def test_get_build_flattened_error(): + client = CloudBuildClient( + 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_build( + cloudbuild.GetBuildRequest(), + project_id='project_id_value', + id='id_value', + ) + + +@pytest.mark.asyncio +async def test_get_build_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_build), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.Build() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.Build()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_build( + project_id='project_id_value', + id='id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].id == 'id_value' + + +@pytest.mark.asyncio +async def test_get_build_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_build( + cloudbuild.GetBuildRequest(), + project_id='project_id_value', + id='id_value', + ) + + +def test_list_builds(transport: str = 'grpc', request_type=cloudbuild.ListBuildsRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_builds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.ListBuildsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_builds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ListBuildsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBuildsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_builds_from_dict(): + test_list_builds(request_type=dict) + + +def test_list_builds_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 = CloudBuildClient( + 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_builds), + '__call__') as call: + client.list_builds() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ListBuildsRequest() + + +@pytest.mark.asyncio +async def test_list_builds_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.ListBuildsRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_builds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListBuildsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_builds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ListBuildsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBuildsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_builds_async_from_dict(): + await test_list_builds_async(request_type=dict) + + +def test_list_builds_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_builds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.ListBuildsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_builds( + project_id='project_id_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].filter == 'filter_value' + + +def test_list_builds_flattened_error(): + client = CloudBuildClient( + 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_builds( + cloudbuild.ListBuildsRequest(), + project_id='project_id_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_builds_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_builds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.ListBuildsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListBuildsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_builds( + project_id='project_id_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_builds_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_builds( + cloudbuild.ListBuildsRequest(), + project_id='project_id_value', + filter='filter_value', + ) + + +def test_list_builds_pager(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_builds), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + cloudbuild.Build(), + cloudbuild.Build(), + ], + next_page_token='abc', + ), + cloudbuild.ListBuildsResponse( + builds=[], + next_page_token='def', + ), + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + ], + next_page_token='ghi', + ), + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + cloudbuild.Build(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_builds(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, cloudbuild.Build) + for i in results) + +def test_list_builds_pages(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_builds), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + cloudbuild.Build(), + cloudbuild.Build(), + ], + next_page_token='abc', + ), + cloudbuild.ListBuildsResponse( + builds=[], + next_page_token='def', + ), + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + ], + next_page_token='ghi', + ), + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + cloudbuild.Build(), + ], + ), + RuntimeError, + ) + pages = list(client.list_builds(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_builds_async_pager(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_builds), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + cloudbuild.Build(), + cloudbuild.Build(), + ], + next_page_token='abc', + ), + cloudbuild.ListBuildsResponse( + builds=[], + next_page_token='def', + ), + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + ], + next_page_token='ghi', + ), + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + cloudbuild.Build(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_builds(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, cloudbuild.Build) + for i in responses) + +@pytest.mark.asyncio +async def test_list_builds_async_pages(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_builds), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + cloudbuild.Build(), + cloudbuild.Build(), + ], + next_page_token='abc', + ), + cloudbuild.ListBuildsResponse( + builds=[], + next_page_token='def', + ), + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + ], + next_page_token='ghi', + ), + cloudbuild.ListBuildsResponse( + builds=[ + cloudbuild.Build(), + cloudbuild.Build(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_builds(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_cancel_build(transport: str = 'grpc', request_type=cloudbuild.CancelBuildRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_build), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.Build( + name='name_value', + id='id_value', + project_id='project_id_value', + status=cloudbuild.Build.Status.QUEUED, + status_detail='status_detail_value', + images=['images_value'], + logs_bucket='logs_bucket_value', + build_trigger_id='build_trigger_id_value', + log_url='log_url_value', + tags=['tags_value'], + service_account='service_account_value', + ) + response = client.cancel_build(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CancelBuildRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.Build) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.project_id == 'project_id_value' + assert response.status == cloudbuild.Build.Status.QUEUED + assert response.status_detail == 'status_detail_value' + assert response.images == ['images_value'] + assert response.logs_bucket == 'logs_bucket_value' + assert response.build_trigger_id == 'build_trigger_id_value' + assert response.log_url == 'log_url_value' + assert response.tags == ['tags_value'] + assert response.service_account == 'service_account_value' + + +def test_cancel_build_from_dict(): + test_cancel_build(request_type=dict) + + +def test_cancel_build_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 = CloudBuildClient( + 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.cancel_build), + '__call__') as call: + client.cancel_build() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CancelBuildRequest() + + +@pytest.mark.asyncio +async def test_cancel_build_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.CancelBuildRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_build), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.Build( + name='name_value', + id='id_value', + project_id='project_id_value', + status=cloudbuild.Build.Status.QUEUED, + status_detail='status_detail_value', + images=['images_value'], + logs_bucket='logs_bucket_value', + build_trigger_id='build_trigger_id_value', + log_url='log_url_value', + tags=['tags_value'], + service_account='service_account_value', + )) + response = await client.cancel_build(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CancelBuildRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.Build) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.project_id == 'project_id_value' + assert response.status == cloudbuild.Build.Status.QUEUED + assert response.status_detail == 'status_detail_value' + assert response.images == ['images_value'] + assert response.logs_bucket == 'logs_bucket_value' + assert response.build_trigger_id == 'build_trigger_id_value' + assert response.log_url == 'log_url_value' + assert response.tags == ['tags_value'] + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_cancel_build_async_from_dict(): + await test_cancel_build_async(request_type=dict) + + +def test_cancel_build_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_build), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.Build() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.cancel_build( + project_id='project_id_value', + id='id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].id == 'id_value' + + +def test_cancel_build_flattened_error(): + client = CloudBuildClient( + 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.cancel_build( + cloudbuild.CancelBuildRequest(), + project_id='project_id_value', + id='id_value', + ) + + +@pytest.mark.asyncio +async def test_cancel_build_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_build), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.Build() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.Build()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.cancel_build( + project_id='project_id_value', + id='id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].id == 'id_value' + + +@pytest.mark.asyncio +async def test_cancel_build_flattened_error_async(): + client = CloudBuildAsyncClient( + 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.cancel_build( + cloudbuild.CancelBuildRequest(), + project_id='project_id_value', + id='id_value', + ) + + +def test_retry_build(transport: str = 'grpc', request_type=cloudbuild.RetryBuildRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retry_build), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.retry_build(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.RetryBuildRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_retry_build_from_dict(): + test_retry_build(request_type=dict) + + +def test_retry_build_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 = CloudBuildClient( + 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.retry_build), + '__call__') as call: + client.retry_build() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.RetryBuildRequest() + + +@pytest.mark.asyncio +async def test_retry_build_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.RetryBuildRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retry_build), + '__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.retry_build(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.RetryBuildRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_retry_build_async_from_dict(): + await test_retry_build_async(request_type=dict) + + +def test_retry_build_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retry_build), + '__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.retry_build( + project_id='project_id_value', + id='id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].id == 'id_value' + + +def test_retry_build_flattened_error(): + client = CloudBuildClient( + 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.retry_build( + cloudbuild.RetryBuildRequest(), + project_id='project_id_value', + id='id_value', + ) + + +@pytest.mark.asyncio +async def test_retry_build_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retry_build), + '__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.retry_build( + project_id='project_id_value', + id='id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].id == 'id_value' + + +@pytest.mark.asyncio +async def test_retry_build_flattened_error_async(): + client = CloudBuildAsyncClient( + 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.retry_build( + cloudbuild.RetryBuildRequest(), + project_id='project_id_value', + id='id_value', + ) + + +def test_create_build_trigger(transport: str = 'grpc', request_type=cloudbuild.CreateBuildTriggerRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.BuildTrigger( + resource_name='resource_name_value', + id='id_value', + description='description_value', + name='name_value', + tags=['tags_value'], + disabled=True, + ignored_files=['ignored_files_value'], + included_files=['included_files_value'], + filter='filter_value', + autodetect=True, + ) + response = client.create_build_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CreateBuildTriggerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.BuildTrigger) + assert response.resource_name == 'resource_name_value' + assert response.id == 'id_value' + assert response.description == 'description_value' + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.disabled is True + assert response.ignored_files == ['ignored_files_value'] + assert response.included_files == ['included_files_value'] + assert response.filter == 'filter_value' + + +def test_create_build_trigger_from_dict(): + test_create_build_trigger(request_type=dict) + + +def test_create_build_trigger_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 = CloudBuildClient( + 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_build_trigger), + '__call__') as call: + client.create_build_trigger() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CreateBuildTriggerRequest() + + +@pytest.mark.asyncio +async def test_create_build_trigger_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.CreateBuildTriggerRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger( + resource_name='resource_name_value', + id='id_value', + description='description_value', + name='name_value', + tags=['tags_value'], + disabled=True, + ignored_files=['ignored_files_value'], + included_files=['included_files_value'], + filter='filter_value', + )) + response = await client.create_build_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CreateBuildTriggerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.BuildTrigger) + assert response.resource_name == 'resource_name_value' + assert response.id == 'id_value' + assert response.description == 'description_value' + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.disabled is True + assert response.ignored_files == ['ignored_files_value'] + assert response.included_files == ['included_files_value'] + assert response.filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_create_build_trigger_async_from_dict(): + await test_create_build_trigger_async(request_type=dict) + + +def test_create_build_trigger_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.BuildTrigger() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_build_trigger( + project_id='project_id_value', + trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].trigger == cloudbuild.BuildTrigger(resource_name='resource_name_value') + + +def test_create_build_trigger_flattened_error(): + client = CloudBuildClient( + 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_build_trigger( + cloudbuild.CreateBuildTriggerRequest(), + project_id='project_id_value', + trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_build_trigger_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.BuildTrigger() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_build_trigger( + project_id='project_id_value', + trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].trigger == cloudbuild.BuildTrigger(resource_name='resource_name_value') + + +@pytest.mark.asyncio +async def test_create_build_trigger_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_build_trigger( + cloudbuild.CreateBuildTriggerRequest(), + project_id='project_id_value', + trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), + ) + + +def test_get_build_trigger(transport: str = 'grpc', request_type=cloudbuild.GetBuildTriggerRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.BuildTrigger( + resource_name='resource_name_value', + id='id_value', + description='description_value', + name='name_value', + tags=['tags_value'], + disabled=True, + ignored_files=['ignored_files_value'], + included_files=['included_files_value'], + filter='filter_value', + autodetect=True, + ) + response = client.get_build_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.GetBuildTriggerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.BuildTrigger) + assert response.resource_name == 'resource_name_value' + assert response.id == 'id_value' + assert response.description == 'description_value' + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.disabled is True + assert response.ignored_files == ['ignored_files_value'] + assert response.included_files == ['included_files_value'] + assert response.filter == 'filter_value' + + +def test_get_build_trigger_from_dict(): + test_get_build_trigger(request_type=dict) + + +def test_get_build_trigger_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 = CloudBuildClient( + 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_build_trigger), + '__call__') as call: + client.get_build_trigger() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.GetBuildTriggerRequest() + + +@pytest.mark.asyncio +async def test_get_build_trigger_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.GetBuildTriggerRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger( + resource_name='resource_name_value', + id='id_value', + description='description_value', + name='name_value', + tags=['tags_value'], + disabled=True, + ignored_files=['ignored_files_value'], + included_files=['included_files_value'], + filter='filter_value', + )) + response = await client.get_build_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.GetBuildTriggerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.BuildTrigger) + assert response.resource_name == 'resource_name_value' + assert response.id == 'id_value' + assert response.description == 'description_value' + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.disabled is True + assert response.ignored_files == ['ignored_files_value'] + assert response.included_files == ['included_files_value'] + assert response.filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_get_build_trigger_async_from_dict(): + await test_get_build_trigger_async(request_type=dict) + + +def test_get_build_trigger_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.BuildTrigger() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_build_trigger( + project_id='project_id_value', + trigger_id='trigger_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].trigger_id == 'trigger_id_value' + + +def test_get_build_trigger_flattened_error(): + client = CloudBuildClient( + 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_build_trigger( + cloudbuild.GetBuildTriggerRequest(), + project_id='project_id_value', + trigger_id='trigger_id_value', + ) + + +@pytest.mark.asyncio +async def test_get_build_trigger_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.BuildTrigger() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_build_trigger( + project_id='project_id_value', + trigger_id='trigger_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].trigger_id == 'trigger_id_value' + + +@pytest.mark.asyncio +async def test_get_build_trigger_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_build_trigger( + cloudbuild.GetBuildTriggerRequest(), + project_id='project_id_value', + trigger_id='trigger_id_value', + ) + + +def test_list_build_triggers(transport: str = 'grpc', request_type=cloudbuild.ListBuildTriggersRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build_triggers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.ListBuildTriggersResponse( + next_page_token='next_page_token_value', + ) + response = client.list_build_triggers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ListBuildTriggersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBuildTriggersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_build_triggers_from_dict(): + test_list_build_triggers(request_type=dict) + + +def test_list_build_triggers_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 = CloudBuildClient( + 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_build_triggers), + '__call__') as call: + client.list_build_triggers() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ListBuildTriggersRequest() + + +@pytest.mark.asyncio +async def test_list_build_triggers_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.ListBuildTriggersRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build_triggers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListBuildTriggersResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_build_triggers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ListBuildTriggersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBuildTriggersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_build_triggers_async_from_dict(): + await test_list_build_triggers_async(request_type=dict) + + +def test_list_build_triggers_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_build_triggers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.ListBuildTriggersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_build_triggers( + project_id='project_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + + +def test_list_build_triggers_flattened_error(): + client = CloudBuildClient( + 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_build_triggers( + cloudbuild.ListBuildTriggersRequest(), + project_id='project_id_value', + ) + + +@pytest.mark.asyncio +async def test_list_build_triggers_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_build_triggers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.ListBuildTriggersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListBuildTriggersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_build_triggers( + project_id='project_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + + +@pytest.mark.asyncio +async def test_list_build_triggers_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_build_triggers( + cloudbuild.ListBuildTriggersRequest(), + project_id='project_id_value', + ) + + +def test_list_build_triggers_pager(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_build_triggers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + ], + next_page_token='abc', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[], + next_page_token='def', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + ], + next_page_token='ghi', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_build_triggers(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, cloudbuild.BuildTrigger) + for i in results) + +def test_list_build_triggers_pages(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_build_triggers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + ], + next_page_token='abc', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[], + next_page_token='def', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + ], + next_page_token='ghi', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + ], + ), + RuntimeError, + ) + pages = list(client.list_build_triggers(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_build_triggers_async_pager(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_build_triggers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + ], + next_page_token='abc', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[], + next_page_token='def', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + ], + next_page_token='ghi', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_build_triggers(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, cloudbuild.BuildTrigger) + for i in responses) + +@pytest.mark.asyncio +async def test_list_build_triggers_async_pages(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_build_triggers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + ], + next_page_token='abc', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[], + next_page_token='def', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + ], + next_page_token='ghi', + ), + cloudbuild.ListBuildTriggersResponse( + triggers=[ + cloudbuild.BuildTrigger(), + cloudbuild.BuildTrigger(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_build_triggers(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_delete_build_trigger(transport: str = 'grpc', request_type=cloudbuild.DeleteBuildTriggerRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_build_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.DeleteBuildTriggerRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_build_trigger_from_dict(): + test_delete_build_trigger(request_type=dict) + + +def test_delete_build_trigger_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 = CloudBuildClient( + 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_build_trigger), + '__call__') as call: + client.delete_build_trigger() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.DeleteBuildTriggerRequest() + + +@pytest.mark.asyncio +async def test_delete_build_trigger_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.DeleteBuildTriggerRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_build_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.DeleteBuildTriggerRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_build_trigger_async_from_dict(): + await test_delete_build_trigger_async(request_type=dict) + + +def test_delete_build_trigger_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_build_trigger( + project_id='project_id_value', + trigger_id='trigger_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].trigger_id == 'trigger_id_value' + + +def test_delete_build_trigger_flattened_error(): + client = CloudBuildClient( + 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_build_trigger( + cloudbuild.DeleteBuildTriggerRequest(), + project_id='project_id_value', + trigger_id='trigger_id_value', + ) + + +@pytest.mark.asyncio +async def test_delete_build_trigger_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_build_trigger( + project_id='project_id_value', + trigger_id='trigger_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].trigger_id == 'trigger_id_value' + + +@pytest.mark.asyncio +async def test_delete_build_trigger_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_build_trigger( + cloudbuild.DeleteBuildTriggerRequest(), + project_id='project_id_value', + trigger_id='trigger_id_value', + ) + + +def test_update_build_trigger(transport: str = 'grpc', request_type=cloudbuild.UpdateBuildTriggerRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.BuildTrigger( + resource_name='resource_name_value', + id='id_value', + description='description_value', + name='name_value', + tags=['tags_value'], + disabled=True, + ignored_files=['ignored_files_value'], + included_files=['included_files_value'], + filter='filter_value', + autodetect=True, + ) + response = client.update_build_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.UpdateBuildTriggerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.BuildTrigger) + assert response.resource_name == 'resource_name_value' + assert response.id == 'id_value' + assert response.description == 'description_value' + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.disabled is True + assert response.ignored_files == ['ignored_files_value'] + assert response.included_files == ['included_files_value'] + assert response.filter == 'filter_value' + + +def test_update_build_trigger_from_dict(): + test_update_build_trigger(request_type=dict) + + +def test_update_build_trigger_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 = CloudBuildClient( + 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_build_trigger), + '__call__') as call: + client.update_build_trigger() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.UpdateBuildTriggerRequest() + + +@pytest.mark.asyncio +async def test_update_build_trigger_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.UpdateBuildTriggerRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger( + resource_name='resource_name_value', + id='id_value', + description='description_value', + name='name_value', + tags=['tags_value'], + disabled=True, + ignored_files=['ignored_files_value'], + included_files=['included_files_value'], + filter='filter_value', + )) + response = await client.update_build_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.UpdateBuildTriggerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.BuildTrigger) + assert response.resource_name == 'resource_name_value' + assert response.id == 'id_value' + assert response.description == 'description_value' + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.disabled is True + assert response.ignored_files == ['ignored_files_value'] + assert response.included_files == ['included_files_value'] + assert response.filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_update_build_trigger_async_from_dict(): + await test_update_build_trigger_async(request_type=dict) + + +def test_update_build_trigger_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.BuildTrigger() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_build_trigger( + project_id='project_id_value', + trigger_id='trigger_id_value', + trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].trigger_id == 'trigger_id_value' + assert args[0].trigger == cloudbuild.BuildTrigger(resource_name='resource_name_value') + + +def test_update_build_trigger_flattened_error(): + client = CloudBuildClient( + 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_build_trigger( + cloudbuild.UpdateBuildTriggerRequest(), + project_id='project_id_value', + trigger_id='trigger_id_value', + trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_build_trigger_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.BuildTrigger() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_build_trigger( + project_id='project_id_value', + trigger_id='trigger_id_value', + trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].trigger_id == 'trigger_id_value' + assert args[0].trigger == cloudbuild.BuildTrigger(resource_name='resource_name_value') + + +@pytest.mark.asyncio +async def test_update_build_trigger_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_build_trigger( + cloudbuild.UpdateBuildTriggerRequest(), + project_id='project_id_value', + trigger_id='trigger_id_value', + trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), + ) + + +def test_run_build_trigger(transport: str = 'grpc', request_type=cloudbuild.RunBuildTriggerRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_build_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_build_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.RunBuildTriggerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_build_trigger_from_dict(): + test_run_build_trigger(request_type=dict) + + +def test_run_build_trigger_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 = CloudBuildClient( + 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.run_build_trigger), + '__call__') as call: + client.run_build_trigger() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.RunBuildTriggerRequest() + + +@pytest.mark.asyncio +async def test_run_build_trigger_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.RunBuildTriggerRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_build_trigger), + '__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.run_build_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.RunBuildTriggerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_build_trigger_async_from_dict(): + await test_run_build_trigger_async(request_type=dict) + + +def test_run_build_trigger_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_build_trigger), + '__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.run_build_trigger( + project_id='project_id_value', + trigger_id='trigger_id_value', + source=cloudbuild.RepoSource(project_id='project_id_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].trigger_id == 'trigger_id_value' + assert args[0].source == cloudbuild.RepoSource(project_id='project_id_value') + + +def test_run_build_trigger_flattened_error(): + client = CloudBuildClient( + 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.run_build_trigger( + cloudbuild.RunBuildTriggerRequest(), + project_id='project_id_value', + trigger_id='trigger_id_value', + source=cloudbuild.RepoSource(project_id='project_id_value'), + ) + + +@pytest.mark.asyncio +async def test_run_build_trigger_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_build_trigger), + '__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.run_build_trigger( + project_id='project_id_value', + trigger_id='trigger_id_value', + source=cloudbuild.RepoSource(project_id='project_id_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].project_id == 'project_id_value' + assert args[0].trigger_id == 'trigger_id_value' + assert args[0].source == cloudbuild.RepoSource(project_id='project_id_value') + + +@pytest.mark.asyncio +async def test_run_build_trigger_flattened_error_async(): + client = CloudBuildAsyncClient( + 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.run_build_trigger( + cloudbuild.RunBuildTriggerRequest(), + project_id='project_id_value', + trigger_id='trigger_id_value', + source=cloudbuild.RepoSource(project_id='project_id_value'), + ) + + +def test_receive_trigger_webhook(transport: str = 'grpc', request_type=cloudbuild.ReceiveTriggerWebhookRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.receive_trigger_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.ReceiveTriggerWebhookResponse( + ) + response = client.receive_trigger_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ReceiveTriggerWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.ReceiveTriggerWebhookResponse) + + +def test_receive_trigger_webhook_from_dict(): + test_receive_trigger_webhook(request_type=dict) + + +def test_receive_trigger_webhook_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 = CloudBuildClient( + 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.receive_trigger_webhook), + '__call__') as call: + client.receive_trigger_webhook() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ReceiveTriggerWebhookRequest() + + +@pytest.mark.asyncio +async def test_receive_trigger_webhook_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.ReceiveTriggerWebhookRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.receive_trigger_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ReceiveTriggerWebhookResponse( + )) + response = await client.receive_trigger_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ReceiveTriggerWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.ReceiveTriggerWebhookResponse) + + +@pytest.mark.asyncio +async def test_receive_trigger_webhook_async_from_dict(): + await test_receive_trigger_webhook_async(request_type=dict) + + +def test_create_worker_pool(transport: str = 'grpc', request_type=cloudbuild.CreateWorkerPoolRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CreateWorkerPoolRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_worker_pool_from_dict(): + test_create_worker_pool(request_type=dict) + + +def test_create_worker_pool_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 = CloudBuildClient( + 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_worker_pool), + '__call__') as call: + client.create_worker_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CreateWorkerPoolRequest() + + +@pytest.mark.asyncio +async def test_create_worker_pool_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.CreateWorkerPoolRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.CreateWorkerPoolRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_worker_pool_async_from_dict(): + await test_create_worker_pool_async(request_type=dict) + + +def test_create_worker_pool_field_headers(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudbuild.CreateWorkerPoolRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_worker_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_worker_pool_field_headers_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudbuild.CreateWorkerPoolRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_worker_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_create_worker_pool_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_worker_pool( + parent='parent_value', + worker_pool=cloudbuild.WorkerPool(name='name_value'), + worker_pool_id='worker_pool_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].worker_pool == cloudbuild.WorkerPool(name='name_value') + assert args[0].worker_pool_id == 'worker_pool_id_value' + + +def test_create_worker_pool_flattened_error(): + client = CloudBuildClient( + 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_worker_pool( + cloudbuild.CreateWorkerPoolRequest(), + parent='parent_value', + worker_pool=cloudbuild.WorkerPool(name='name_value'), + worker_pool_id='worker_pool_id_value', + ) + + +@pytest.mark.asyncio +async def test_create_worker_pool_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_worker_pool( + parent='parent_value', + worker_pool=cloudbuild.WorkerPool(name='name_value'), + worker_pool_id='worker_pool_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].worker_pool == cloudbuild.WorkerPool(name='name_value') + assert args[0].worker_pool_id == 'worker_pool_id_value' + + +@pytest.mark.asyncio +async def test_create_worker_pool_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_worker_pool( + cloudbuild.CreateWorkerPoolRequest(), + parent='parent_value', + worker_pool=cloudbuild.WorkerPool(name='name_value'), + worker_pool_id='worker_pool_id_value', + ) + + +def test_get_worker_pool(transport: str = 'grpc', request_type=cloudbuild.GetWorkerPoolRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.WorkerPool( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=cloudbuild.WorkerPool.State.CREATING, + etag='etag_value', + private_pool_v1_config=cloudbuild.PrivatePoolV1Config(worker_config=cloudbuild.PrivatePoolV1Config.WorkerConfig(machine_type='machine_type_value')), + ) + response = client.get_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.GetWorkerPoolRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.WorkerPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == cloudbuild.WorkerPool.State.CREATING + assert response.etag == 'etag_value' + + +def test_get_worker_pool_from_dict(): + test_get_worker_pool(request_type=dict) + + +def test_get_worker_pool_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 = CloudBuildClient( + 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_worker_pool), + '__call__') as call: + client.get_worker_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.GetWorkerPoolRequest() + + +@pytest.mark.asyncio +async def test_get_worker_pool_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.GetWorkerPoolRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.WorkerPool( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=cloudbuild.WorkerPool.State.CREATING, + etag='etag_value', + )) + response = await client.get_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.GetWorkerPoolRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, cloudbuild.WorkerPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == cloudbuild.WorkerPool.State.CREATING + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_worker_pool_async_from_dict(): + await test_get_worker_pool_async(request_type=dict) + + +def test_get_worker_pool_field_headers(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudbuild.GetWorkerPoolRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_worker_pool), + '__call__') as call: + call.return_value = cloudbuild.WorkerPool() + client.get_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_worker_pool_field_headers_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudbuild.GetWorkerPoolRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_worker_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.WorkerPool()) + await client.get_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_worker_pool_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.WorkerPool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_worker_pool( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_worker_pool_flattened_error(): + client = CloudBuildClient( + 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_worker_pool( + cloudbuild.GetWorkerPoolRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_worker_pool_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.WorkerPool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.WorkerPool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_worker_pool( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_worker_pool_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_worker_pool( + cloudbuild.GetWorkerPoolRequest(), + name='name_value', + ) + + +def test_delete_worker_pool(transport: str = 'grpc', request_type=cloudbuild.DeleteWorkerPoolRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.DeleteWorkerPoolRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_worker_pool_from_dict(): + test_delete_worker_pool(request_type=dict) + + +def test_delete_worker_pool_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 = CloudBuildClient( + 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_worker_pool), + '__call__') as call: + client.delete_worker_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.DeleteWorkerPoolRequest() + + +@pytest.mark.asyncio +async def test_delete_worker_pool_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.DeleteWorkerPoolRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.DeleteWorkerPoolRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_worker_pool_async_from_dict(): + await test_delete_worker_pool_async(request_type=dict) + + +def test_delete_worker_pool_field_headers(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudbuild.DeleteWorkerPoolRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_worker_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_worker_pool_field_headers_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudbuild.DeleteWorkerPoolRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_worker_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_worker_pool_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_worker_pool( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_delete_worker_pool_flattened_error(): + client = CloudBuildClient( + 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_worker_pool( + cloudbuild.DeleteWorkerPoolRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_worker_pool_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_worker_pool( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_worker_pool_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_worker_pool( + cloudbuild.DeleteWorkerPoolRequest(), + name='name_value', + ) + + +def test_update_worker_pool(transport: str = 'grpc', request_type=cloudbuild.UpdateWorkerPoolRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.UpdateWorkerPoolRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_worker_pool_from_dict(): + test_update_worker_pool(request_type=dict) + + +def test_update_worker_pool_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 = CloudBuildClient( + 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_worker_pool), + '__call__') as call: + client.update_worker_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.UpdateWorkerPoolRequest() + + +@pytest.mark.asyncio +async def test_update_worker_pool_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.UpdateWorkerPoolRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.UpdateWorkerPoolRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_worker_pool_async_from_dict(): + await test_update_worker_pool_async(request_type=dict) + + +def test_update_worker_pool_field_headers(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudbuild.UpdateWorkerPoolRequest() + + request.worker_pool.name = 'worker_pool.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_worker_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'worker_pool.name=worker_pool.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_worker_pool_field_headers_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudbuild.UpdateWorkerPoolRequest() + + request.worker_pool.name = 'worker_pool.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_worker_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_worker_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'worker_pool.name=worker_pool.name/value', + ) in kw['metadata'] + + +def test_update_worker_pool_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_worker_pool( + worker_pool=cloudbuild.WorkerPool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].worker_pool == cloudbuild.WorkerPool(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_worker_pool_flattened_error(): + client = CloudBuildClient( + 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_worker_pool( + cloudbuild.UpdateWorkerPoolRequest(), + worker_pool=cloudbuild.WorkerPool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_worker_pool_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_worker_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_worker_pool( + worker_pool=cloudbuild.WorkerPool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].worker_pool == cloudbuild.WorkerPool(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_worker_pool_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_worker_pool( + cloudbuild.UpdateWorkerPoolRequest(), + worker_pool=cloudbuild.WorkerPool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_worker_pools(transport: str = 'grpc', request_type=cloudbuild.ListWorkerPoolsRequest): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_worker_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.ListWorkerPoolsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_worker_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ListWorkerPoolsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkerPoolsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_worker_pools_from_dict(): + test_list_worker_pools(request_type=dict) + + +def test_list_worker_pools_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 = CloudBuildClient( + 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_worker_pools), + '__call__') as call: + client.list_worker_pools() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ListWorkerPoolsRequest() + + +@pytest.mark.asyncio +async def test_list_worker_pools_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.ListWorkerPoolsRequest): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_worker_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListWorkerPoolsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_worker_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloudbuild.ListWorkerPoolsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkerPoolsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_worker_pools_async_from_dict(): + await test_list_worker_pools_async(request_type=dict) + + +def test_list_worker_pools_field_headers(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudbuild.ListWorkerPoolsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_worker_pools), + '__call__') as call: + call.return_value = cloudbuild.ListWorkerPoolsResponse() + client.list_worker_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_worker_pools_field_headers_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudbuild.ListWorkerPoolsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_worker_pools), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListWorkerPoolsResponse()) + await client.list_worker_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_worker_pools_flattened(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_worker_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.ListWorkerPoolsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_worker_pools( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_worker_pools_flattened_error(): + client = CloudBuildClient( + 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_worker_pools( + cloudbuild.ListWorkerPoolsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_worker_pools_flattened_async(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_worker_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = cloudbuild.ListWorkerPoolsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListWorkerPoolsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_worker_pools( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_worker_pools_flattened_error_async(): + client = CloudBuildAsyncClient( + 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_worker_pools( + cloudbuild.ListWorkerPoolsRequest(), + parent='parent_value', + ) + + +def test_list_worker_pools_pager(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_worker_pools), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + ], + next_page_token='abc', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[], + next_page_token='def', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + ], + next_page_token='ghi', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_worker_pools(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, cloudbuild.WorkerPool) + for i in results) + +def test_list_worker_pools_pages(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_worker_pools), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + ], + next_page_token='abc', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[], + next_page_token='def', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + ], + next_page_token='ghi', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + ], + ), + RuntimeError, + ) + pages = list(client.list_worker_pools(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_worker_pools_async_pager(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_worker_pools), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + ], + next_page_token='abc', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[], + next_page_token='def', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + ], + next_page_token='ghi', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_worker_pools(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, cloudbuild.WorkerPool) + for i in responses) + +@pytest.mark.asyncio +async def test_list_worker_pools_async_pages(): + client = CloudBuildAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_worker_pools), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + ], + next_page_token='abc', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[], + next_page_token='def', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + ], + next_page_token='ghi', + ), + cloudbuild.ListWorkerPoolsResponse( + worker_pools=[ + cloudbuild.WorkerPool(), + cloudbuild.WorkerPool(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_worker_pools(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudBuildGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudBuildGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudBuildClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudBuildGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudBuildClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudBuildGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudBuildClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudBuildGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudBuildGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CloudBuildGrpcTransport, + transports.CloudBuildGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudBuildGrpcTransport, + ) + +def test_cloud_build_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudBuildTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_cloud_build_base_transport(): + # Instantiate the base transport. + with mock.patch('google.devtools.cloudbuild_v1.services.cloud_build.transports.CloudBuildTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CloudBuildTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_build', + 'get_build', + 'list_builds', + 'cancel_build', + 'retry_build', + 'create_build_trigger', + 'get_build_trigger', + 'list_build_triggers', + 'delete_build_trigger', + 'update_build_trigger', + 'run_build_trigger', + 'receive_trigger_webhook', + 'create_worker_pool', + 'get_worker_pool', + 'delete_worker_pool', + 'update_worker_pool', + 'list_worker_pools', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_cloud_build_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.devtools.cloudbuild_v1.services.cloud_build.transports.CloudBuildTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudBuildTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_cloud_build_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.devtools.cloudbuild_v1.services.cloud_build.transports.CloudBuildTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudBuildTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_cloud_build_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.devtools.cloudbuild_v1.services.cloud_build.transports.CloudBuildTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudBuildTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_cloud_build_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) + CloudBuildClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_cloud_build_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudBuildClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudBuildGrpcTransport, + transports.CloudBuildGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_cloud_build_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.CloudBuildGrpcTransport, + transports.CloudBuildGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_cloud_build_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudBuildGrpcTransport, grpc_helpers), + (transports.CloudBuildGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_cloud_build_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( + "cloudbuild.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="cloudbuild.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CloudBuildGrpcTransport, transports.CloudBuildGrpcAsyncIOTransport]) +def test_cloud_build_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_cloud_build_host_no_port(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudbuild.googleapis.com'), + ) + assert client.transport._host == 'cloudbuild.googleapis.com:443' + + +def test_cloud_build_host_with_port(): + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudbuild.googleapis.com:8000'), + ) + assert client.transport._host == 'cloudbuild.googleapis.com:8000' + +def test_cloud_build_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudBuildGrpcTransport( + 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_build_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudBuildGrpcAsyncIOTransport( + 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.CloudBuildGrpcTransport, transports.CloudBuildGrpcAsyncIOTransport]) +def test_cloud_build_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.CloudBuildGrpcTransport, transports.CloudBuildGrpcAsyncIOTransport]) +def test_cloud_build_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_build_grpc_lro_client(): + client = CloudBuildClient( + 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_build_grpc_lro_async_client(): + client = CloudBuildAsyncClient( + 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" + build = "clam" + expected = "projects/{project}/builds/{build}".format(project=project, build=build, ) + actual = CloudBuildClient.build_path(project, build) + assert expected == actual + + +def test_parse_build_path(): + expected = { + "project": "whelk", + "build": "octopus", + } + path = CloudBuildClient.build_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_build_path(path) + assert expected == actual + +def test_build_trigger_path(): + project = "oyster" + trigger = "nudibranch" + expected = "projects/{project}/triggers/{trigger}".format(project=project, trigger=trigger, ) + actual = CloudBuildClient.build_trigger_path(project, trigger) + assert expected == actual + + +def test_parse_build_trigger_path(): + expected = { + "project": "cuttlefish", + "trigger": "mussel", + } + path = CloudBuildClient.build_trigger_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_build_trigger_path(path) + assert expected == actual + +def test_crypto_key_path(): + project = "winkle" + location = "nautilus" + keyring = "scallop" + key = "abalone" + expected = "projects/{project}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}".format(project=project, location=location, keyring=keyring, key=key, ) + actual = CloudBuildClient.crypto_key_path(project, location, keyring, key) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "squid", + "location": "clam", + "keyring": "whelk", + "key": "octopus", + } + path = CloudBuildClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_crypto_key_path(path) + assert expected == actual + +def test_network_path(): + project = "oyster" + network = "nudibranch" + expected = "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + actual = CloudBuildClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "cuttlefish", + "network": "mussel", + } + path = CloudBuildClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_network_path(path) + assert expected == actual + +def test_secret_version_path(): + project = "winkle" + secret = "nautilus" + version = "scallop" + expected = "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) + actual = CloudBuildClient.secret_version_path(project, secret, version) + assert expected == actual + + +def test_parse_secret_version_path(): + expected = { + "project": "abalone", + "secret": "squid", + "version": "clam", + } + path = CloudBuildClient.secret_version_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_secret_version_path(path) + assert expected == actual + +def test_service_account_path(): + project = "whelk" + service_account = "octopus" + expected = "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + actual = CloudBuildClient.service_account_path(project, service_account) + assert expected == actual + + +def test_parse_service_account_path(): + expected = { + "project": "oyster", + "service_account": "nudibranch", + } + path = CloudBuildClient.service_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_service_account_path(path) + assert expected == actual + +def test_subscription_path(): + project = "cuttlefish" + subscription = "mussel" + expected = "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) + actual = CloudBuildClient.subscription_path(project, subscription) + assert expected == actual + + +def test_parse_subscription_path(): + expected = { + "project": "winkle", + "subscription": "nautilus", + } + path = CloudBuildClient.subscription_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_subscription_path(path) + assert expected == actual + +def test_topic_path(): + project = "scallop" + topic = "abalone" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = CloudBuildClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "squid", + "topic": "clam", + } + path = CloudBuildClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_topic_path(path) + assert expected == actual + +def test_worker_pool_path(): + project = "whelk" + location = "octopus" + worker_pool = "oyster" + expected = "projects/{project}/locations/{location}/workerPools/{worker_pool}".format(project=project, location=location, worker_pool=worker_pool, ) + actual = CloudBuildClient.worker_pool_path(project, location, worker_pool) + assert expected == actual + + +def test_parse_worker_pool_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "worker_pool": "mussel", + } + path = CloudBuildClient.worker_pool_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_worker_pool_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CloudBuildClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = CloudBuildClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = CloudBuildClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = CloudBuildClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CloudBuildClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = CloudBuildClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = CloudBuildClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = CloudBuildClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.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 = CloudBuildClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = CloudBuildClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudBuildClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CloudBuildTransport, '_prep_wrapped_messages') as prep: + client = CloudBuildClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CloudBuildTransport, '_prep_wrapped_messages') as prep: + transport_class = CloudBuildClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) From befd55c6af9271a36afa9ed75deebe36f3174cbb Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 23 Jul 2021 21:23:48 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md --- .../services/cloud_build/client.py | 4 + owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - .../v1/docs/cloudbuild_v1/cloud_build.rst | 10 - .../v1/docs/cloudbuild_v1/services.rst | 6 - .../v1/docs/cloudbuild_v1/types.rst | 7 - owl-bot-staging/v1/docs/conf.py | 376 -- owl-bot-staging/v1/docs/index.rst | 7 - .../v1/google/devtools/cloudbuild/__init__.py | 129 - .../v1/google/devtools/cloudbuild/py.typed | 2 - .../google/devtools/cloudbuild_v1/__init__.py | 130 - .../cloudbuild_v1/gapic_metadata.json | 193 - .../v1/google/devtools/cloudbuild_v1/py.typed | 2 - .../cloudbuild_v1/services/__init__.py | 15 - .../services/cloud_build/__init__.py | 22 - .../services/cloud_build/async_client.py | 1824 ------ .../services/cloud_build/client.py | 2039 ------- .../services/cloud_build/pagers.py | 384 -- .../cloud_build/transports/__init__.py | 33 - .../services/cloud_build/transports/base.py | 449 -- .../services/cloud_build/transports/grpc.py | 745 --- .../cloud_build/transports/grpc_asyncio.py | 749 --- .../devtools/cloudbuild_v1/types/__init__.py | 126 - .../cloudbuild_v1/types/cloudbuild.py | 2693 --------- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../scripts/fixup_cloudbuild_v1_keywords.py | 192 - owl-bot-staging/v1/setup.py | 54 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/cloudbuild_v1/__init__.py | 16 - .../gapic/cloudbuild_v1/test_cloud_build.py | 5062 ----------------- .../gapic/cloudbuild_v1/test_cloud_build.py | 29 +- 35 files changed, 22 insertions(+), 15527 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/cloudbuild_v1/cloud_build.rst delete mode 100644 owl-bot-staging/v1/docs/cloudbuild_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/cloudbuild_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild/__init__.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild/py.typed delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/__init__.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/async_client.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/client.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/pagers.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/base.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/cloudbuild.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/scripts/fixup_cloudbuild_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/cloudbuild_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py diff --git a/google/cloud/devtools/cloudbuild_v1/services/cloud_build/client.py b/google/cloud/devtools/cloudbuild_v1/services/cloud_build/client.py index 7498b7a1..a4c382f0 100644 --- a/google/cloud/devtools/cloudbuild_v1/services/cloud_build/client.py +++ b/google/cloud/devtools/cloudbuild_v1/services/cloud_build/client.py @@ -469,6 +469,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def create_build( diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 0bca5911..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/devtools/cloudbuild/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 7e2b155f..00000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/devtools/cloudbuild *.py -recursive-include google/devtools/cloudbuild_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index d4e3fd01..00000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Devtools Cloudbuild 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 Devtools Cloudbuild 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/cloudbuild_v1/cloud_build.rst b/owl-bot-staging/v1/docs/cloudbuild_v1/cloud_build.rst deleted file mode 100644 index 1e69b936..00000000 --- a/owl-bot-staging/v1/docs/cloudbuild_v1/cloud_build.rst +++ /dev/null @@ -1,10 +0,0 @@ -CloudBuild ----------------------------- - -.. automodule:: google.devtools.cloudbuild_v1.services.cloud_build - :members: - :inherited-members: - -.. automodule:: google.devtools.cloudbuild_v1.services.cloud_build.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/cloudbuild_v1/services.rst b/owl-bot-staging/v1/docs/cloudbuild_v1/services.rst deleted file mode 100644 index 87309bc9..00000000 --- a/owl-bot-staging/v1/docs/cloudbuild_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Devtools Cloudbuild v1 API -============================================== -.. toctree:: - :maxdepth: 2 - - cloud_build diff --git a/owl-bot-staging/v1/docs/cloudbuild_v1/types.rst b/owl-bot-staging/v1/docs/cloudbuild_v1/types.rst deleted file mode 100644 index c865836d..00000000 --- a/owl-bot-staging/v1/docs/cloudbuild_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Devtools Cloudbuild v1 API -=========================================== - -.. automodule:: google.devtools.cloudbuild_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 6d4458bc..00000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-devtools-cloudbuild documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-devtools-cloudbuild" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Devtools 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-devtools-cloudbuild-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-devtools-cloudbuild.tex", - u"google-devtools-cloudbuild Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-devtools-cloudbuild", - u"Google Devtools Cloudbuild Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-devtools-cloudbuild", - u"google-devtools-cloudbuild Documentation", - author, - "google-devtools-cloudbuild", - "GAPIC library for Google Devtools Cloudbuild API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index 37eed237..00000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - cloudbuild_v1/services - cloudbuild_v1/types diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild/__init__.py deleted file mode 100644 index 832cf1fb..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild/__init__.py +++ /dev/null @@ -1,129 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.devtools.cloudbuild_v1.services.cloud_build.client import CloudBuildClient -from google.devtools.cloudbuild_v1.services.cloud_build.async_client import CloudBuildAsyncClient - -from google.devtools.cloudbuild_v1.types.cloudbuild import ArtifactResult -from google.devtools.cloudbuild_v1.types.cloudbuild import Artifacts -from google.devtools.cloudbuild_v1.types.cloudbuild import Build -from google.devtools.cloudbuild_v1.types.cloudbuild import BuildOperationMetadata -from google.devtools.cloudbuild_v1.types.cloudbuild import BuildOptions -from google.devtools.cloudbuild_v1.types.cloudbuild import BuildStep -from google.devtools.cloudbuild_v1.types.cloudbuild import BuildTrigger -from google.devtools.cloudbuild_v1.types.cloudbuild import BuiltImage -from google.devtools.cloudbuild_v1.types.cloudbuild import CancelBuildRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import CreateBuildRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import CreateBuildTriggerRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import CreateWorkerPoolOperationMetadata -from google.devtools.cloudbuild_v1.types.cloudbuild import CreateWorkerPoolRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import DeleteBuildTriggerRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import DeleteWorkerPoolOperationMetadata -from google.devtools.cloudbuild_v1.types.cloudbuild import DeleteWorkerPoolRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import FileHashes -from google.devtools.cloudbuild_v1.types.cloudbuild import GetBuildRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import GetBuildTriggerRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import GetWorkerPoolRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import GitHubEventsConfig -from google.devtools.cloudbuild_v1.types.cloudbuild import Hash -from google.devtools.cloudbuild_v1.types.cloudbuild import InlineSecret -from google.devtools.cloudbuild_v1.types.cloudbuild import ListBuildsRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import ListBuildsResponse -from google.devtools.cloudbuild_v1.types.cloudbuild import ListBuildTriggersRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import ListBuildTriggersResponse -from google.devtools.cloudbuild_v1.types.cloudbuild import ListWorkerPoolsRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import ListWorkerPoolsResponse -from google.devtools.cloudbuild_v1.types.cloudbuild import PrivatePoolV1Config -from google.devtools.cloudbuild_v1.types.cloudbuild import PubsubConfig -from google.devtools.cloudbuild_v1.types.cloudbuild import PullRequestFilter -from google.devtools.cloudbuild_v1.types.cloudbuild import PushFilter -from google.devtools.cloudbuild_v1.types.cloudbuild import ReceiveTriggerWebhookRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import ReceiveTriggerWebhookResponse -from google.devtools.cloudbuild_v1.types.cloudbuild import RepoSource -from google.devtools.cloudbuild_v1.types.cloudbuild import Results -from google.devtools.cloudbuild_v1.types.cloudbuild import RetryBuildRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import RunBuildTriggerRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import Secret -from google.devtools.cloudbuild_v1.types.cloudbuild import SecretManagerSecret -from google.devtools.cloudbuild_v1.types.cloudbuild import Secrets -from google.devtools.cloudbuild_v1.types.cloudbuild import Source -from google.devtools.cloudbuild_v1.types.cloudbuild import SourceProvenance -from google.devtools.cloudbuild_v1.types.cloudbuild import StorageSource -from google.devtools.cloudbuild_v1.types.cloudbuild import StorageSourceManifest -from google.devtools.cloudbuild_v1.types.cloudbuild import TimeSpan -from google.devtools.cloudbuild_v1.types.cloudbuild import UpdateBuildTriggerRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import UpdateWorkerPoolOperationMetadata -from google.devtools.cloudbuild_v1.types.cloudbuild import UpdateWorkerPoolRequest -from google.devtools.cloudbuild_v1.types.cloudbuild import Volume -from google.devtools.cloudbuild_v1.types.cloudbuild import WebhookConfig -from google.devtools.cloudbuild_v1.types.cloudbuild import WorkerPool - -__all__ = ('CloudBuildClient', - 'CloudBuildAsyncClient', - 'ArtifactResult', - 'Artifacts', - 'Build', - 'BuildOperationMetadata', - 'BuildOptions', - 'BuildStep', - 'BuildTrigger', - 'BuiltImage', - 'CancelBuildRequest', - 'CreateBuildRequest', - 'CreateBuildTriggerRequest', - 'CreateWorkerPoolOperationMetadata', - 'CreateWorkerPoolRequest', - 'DeleteBuildTriggerRequest', - 'DeleteWorkerPoolOperationMetadata', - 'DeleteWorkerPoolRequest', - 'FileHashes', - 'GetBuildRequest', - 'GetBuildTriggerRequest', - 'GetWorkerPoolRequest', - 'GitHubEventsConfig', - 'Hash', - 'InlineSecret', - 'ListBuildsRequest', - 'ListBuildsResponse', - 'ListBuildTriggersRequest', - 'ListBuildTriggersResponse', - 'ListWorkerPoolsRequest', - 'ListWorkerPoolsResponse', - 'PrivatePoolV1Config', - 'PubsubConfig', - 'PullRequestFilter', - 'PushFilter', - 'ReceiveTriggerWebhookRequest', - 'ReceiveTriggerWebhookResponse', - 'RepoSource', - 'Results', - 'RetryBuildRequest', - 'RunBuildTriggerRequest', - 'Secret', - 'SecretManagerSecret', - 'Secrets', - 'Source', - 'SourceProvenance', - 'StorageSource', - 'StorageSourceManifest', - 'TimeSpan', - 'UpdateBuildTriggerRequest', - 'UpdateWorkerPoolOperationMetadata', - 'UpdateWorkerPoolRequest', - 'Volume', - 'WebhookConfig', - 'WorkerPool', -) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild/py.typed b/owl-bot-staging/v1/google/devtools/cloudbuild/py.typed deleted file mode 100644 index 076585a1..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-devtools-cloudbuild package uses inline types. diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/__init__.py deleted file mode 100644 index e5293946..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/__init__.py +++ /dev/null @@ -1,130 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.cloud_build import CloudBuildClient -from .services.cloud_build import CloudBuildAsyncClient - -from .types.cloudbuild import ArtifactResult -from .types.cloudbuild import Artifacts -from .types.cloudbuild import Build -from .types.cloudbuild import BuildOperationMetadata -from .types.cloudbuild import BuildOptions -from .types.cloudbuild import BuildStep -from .types.cloudbuild import BuildTrigger -from .types.cloudbuild import BuiltImage -from .types.cloudbuild import CancelBuildRequest -from .types.cloudbuild import CreateBuildRequest -from .types.cloudbuild import CreateBuildTriggerRequest -from .types.cloudbuild import CreateWorkerPoolOperationMetadata -from .types.cloudbuild import CreateWorkerPoolRequest -from .types.cloudbuild import DeleteBuildTriggerRequest -from .types.cloudbuild import DeleteWorkerPoolOperationMetadata -from .types.cloudbuild import DeleteWorkerPoolRequest -from .types.cloudbuild import FileHashes -from .types.cloudbuild import GetBuildRequest -from .types.cloudbuild import GetBuildTriggerRequest -from .types.cloudbuild import GetWorkerPoolRequest -from .types.cloudbuild import GitHubEventsConfig -from .types.cloudbuild import Hash -from .types.cloudbuild import InlineSecret -from .types.cloudbuild import ListBuildsRequest -from .types.cloudbuild import ListBuildsResponse -from .types.cloudbuild import ListBuildTriggersRequest -from .types.cloudbuild import ListBuildTriggersResponse -from .types.cloudbuild import ListWorkerPoolsRequest -from .types.cloudbuild import ListWorkerPoolsResponse -from .types.cloudbuild import PrivatePoolV1Config -from .types.cloudbuild import PubsubConfig -from .types.cloudbuild import PullRequestFilter -from .types.cloudbuild import PushFilter -from .types.cloudbuild import ReceiveTriggerWebhookRequest -from .types.cloudbuild import ReceiveTriggerWebhookResponse -from .types.cloudbuild import RepoSource -from .types.cloudbuild import Results -from .types.cloudbuild import RetryBuildRequest -from .types.cloudbuild import RunBuildTriggerRequest -from .types.cloudbuild import Secret -from .types.cloudbuild import SecretManagerSecret -from .types.cloudbuild import Secrets -from .types.cloudbuild import Source -from .types.cloudbuild import SourceProvenance -from .types.cloudbuild import StorageSource -from .types.cloudbuild import StorageSourceManifest -from .types.cloudbuild import TimeSpan -from .types.cloudbuild import UpdateBuildTriggerRequest -from .types.cloudbuild import UpdateWorkerPoolOperationMetadata -from .types.cloudbuild import UpdateWorkerPoolRequest -from .types.cloudbuild import Volume -from .types.cloudbuild import WebhookConfig -from .types.cloudbuild import WorkerPool - -__all__ = ( - 'CloudBuildAsyncClient', -'ArtifactResult', -'Artifacts', -'Build', -'BuildOperationMetadata', -'BuildOptions', -'BuildStep', -'BuildTrigger', -'BuiltImage', -'CancelBuildRequest', -'CloudBuildClient', -'CreateBuildRequest', -'CreateBuildTriggerRequest', -'CreateWorkerPoolOperationMetadata', -'CreateWorkerPoolRequest', -'DeleteBuildTriggerRequest', -'DeleteWorkerPoolOperationMetadata', -'DeleteWorkerPoolRequest', -'FileHashes', -'GetBuildRequest', -'GetBuildTriggerRequest', -'GetWorkerPoolRequest', -'GitHubEventsConfig', -'Hash', -'InlineSecret', -'ListBuildTriggersRequest', -'ListBuildTriggersResponse', -'ListBuildsRequest', -'ListBuildsResponse', -'ListWorkerPoolsRequest', -'ListWorkerPoolsResponse', -'PrivatePoolV1Config', -'PubsubConfig', -'PullRequestFilter', -'PushFilter', -'ReceiveTriggerWebhookRequest', -'ReceiveTriggerWebhookResponse', -'RepoSource', -'Results', -'RetryBuildRequest', -'RunBuildTriggerRequest', -'Secret', -'SecretManagerSecret', -'Secrets', -'Source', -'SourceProvenance', -'StorageSource', -'StorageSourceManifest', -'TimeSpan', -'UpdateBuildTriggerRequest', -'UpdateWorkerPoolOperationMetadata', -'UpdateWorkerPoolRequest', -'Volume', -'WebhookConfig', -'WorkerPool', -) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/gapic_metadata.json b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/gapic_metadata.json deleted file mode 100644 index e2f307b5..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/gapic_metadata.json +++ /dev/null @@ -1,193 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.devtools.cloudbuild_v1", - "protoPackage": "google.devtools.cloudbuild.v1", - "schema": "1.0", - "services": { - "CloudBuild": { - "clients": { - "grpc": { - "libraryClient": "CloudBuildClient", - "rpcs": { - "CancelBuild": { - "methods": [ - "cancel_build" - ] - }, - "CreateBuild": { - "methods": [ - "create_build" - ] - }, - "CreateBuildTrigger": { - "methods": [ - "create_build_trigger" - ] - }, - "CreateWorkerPool": { - "methods": [ - "create_worker_pool" - ] - }, - "DeleteBuildTrigger": { - "methods": [ - "delete_build_trigger" - ] - }, - "DeleteWorkerPool": { - "methods": [ - "delete_worker_pool" - ] - }, - "GetBuild": { - "methods": [ - "get_build" - ] - }, - "GetBuildTrigger": { - "methods": [ - "get_build_trigger" - ] - }, - "GetWorkerPool": { - "methods": [ - "get_worker_pool" - ] - }, - "ListBuildTriggers": { - "methods": [ - "list_build_triggers" - ] - }, - "ListBuilds": { - "methods": [ - "list_builds" - ] - }, - "ListWorkerPools": { - "methods": [ - "list_worker_pools" - ] - }, - "ReceiveTriggerWebhook": { - "methods": [ - "receive_trigger_webhook" - ] - }, - "RetryBuild": { - "methods": [ - "retry_build" - ] - }, - "RunBuildTrigger": { - "methods": [ - "run_build_trigger" - ] - }, - "UpdateBuildTrigger": { - "methods": [ - "update_build_trigger" - ] - }, - "UpdateWorkerPool": { - "methods": [ - "update_worker_pool" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CloudBuildAsyncClient", - "rpcs": { - "CancelBuild": { - "methods": [ - "cancel_build" - ] - }, - "CreateBuild": { - "methods": [ - "create_build" - ] - }, - "CreateBuildTrigger": { - "methods": [ - "create_build_trigger" - ] - }, - "CreateWorkerPool": { - "methods": [ - "create_worker_pool" - ] - }, - "DeleteBuildTrigger": { - "methods": [ - "delete_build_trigger" - ] - }, - "DeleteWorkerPool": { - "methods": [ - "delete_worker_pool" - ] - }, - "GetBuild": { - "methods": [ - "get_build" - ] - }, - "GetBuildTrigger": { - "methods": [ - "get_build_trigger" - ] - }, - "GetWorkerPool": { - "methods": [ - "get_worker_pool" - ] - }, - "ListBuildTriggers": { - "methods": [ - "list_build_triggers" - ] - }, - "ListBuilds": { - "methods": [ - "list_builds" - ] - }, - "ListWorkerPools": { - "methods": [ - "list_worker_pools" - ] - }, - "ReceiveTriggerWebhook": { - "methods": [ - "receive_trigger_webhook" - ] - }, - "RetryBuild": { - "methods": [ - "retry_build" - ] - }, - "RunBuildTrigger": { - "methods": [ - "run_build_trigger" - ] - }, - "UpdateBuildTrigger": { - "methods": [ - "update_build_trigger" - ] - }, - "UpdateWorkerPool": { - "methods": [ - "update_worker_pool" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/py.typed b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/py.typed deleted file mode 100644 index 076585a1..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-devtools-cloudbuild package uses inline types. diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/__init__.py deleted file mode 100644 index 2da912a7..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CloudBuildClient -from .async_client import CloudBuildAsyncClient - -__all__ = ( - 'CloudBuildClient', - 'CloudBuildAsyncClient', -) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/async_client.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/async_client.py deleted file mode 100644 index f302ab32..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/async_client.py +++ /dev/null @@ -1,1824 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.devtools.cloudbuild_v1.services.cloud_build import pagers -from google.devtools.cloudbuild_v1.types import cloudbuild -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CloudBuildTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CloudBuildGrpcAsyncIOTransport -from .client import CloudBuildClient - - -class CloudBuildAsyncClient: - """Creates and manages builds on Google Cloud Platform. - - The main concept used by this API is a ``Build``, which describes - the location of the source to build, how to build the source, and - where to store the built artifacts, if any. - - A user can list previously-requested builds or get builds by their - ID to determine the status of the build. - """ - - _client: CloudBuildClient - - DEFAULT_ENDPOINT = CloudBuildClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CloudBuildClient.DEFAULT_MTLS_ENDPOINT - - build_path = staticmethod(CloudBuildClient.build_path) - parse_build_path = staticmethod(CloudBuildClient.parse_build_path) - build_trigger_path = staticmethod(CloudBuildClient.build_trigger_path) - parse_build_trigger_path = staticmethod(CloudBuildClient.parse_build_trigger_path) - crypto_key_path = staticmethod(CloudBuildClient.crypto_key_path) - parse_crypto_key_path = staticmethod(CloudBuildClient.parse_crypto_key_path) - network_path = staticmethod(CloudBuildClient.network_path) - parse_network_path = staticmethod(CloudBuildClient.parse_network_path) - secret_version_path = staticmethod(CloudBuildClient.secret_version_path) - parse_secret_version_path = staticmethod(CloudBuildClient.parse_secret_version_path) - service_account_path = staticmethod(CloudBuildClient.service_account_path) - parse_service_account_path = staticmethod(CloudBuildClient.parse_service_account_path) - subscription_path = staticmethod(CloudBuildClient.subscription_path) - parse_subscription_path = staticmethod(CloudBuildClient.parse_subscription_path) - topic_path = staticmethod(CloudBuildClient.topic_path) - parse_topic_path = staticmethod(CloudBuildClient.parse_topic_path) - worker_pool_path = staticmethod(CloudBuildClient.worker_pool_path) - parse_worker_pool_path = staticmethod(CloudBuildClient.parse_worker_pool_path) - common_billing_account_path = staticmethod(CloudBuildClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CloudBuildClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CloudBuildClient.common_folder_path) - parse_common_folder_path = staticmethod(CloudBuildClient.parse_common_folder_path) - common_organization_path = staticmethod(CloudBuildClient.common_organization_path) - parse_common_organization_path = staticmethod(CloudBuildClient.parse_common_organization_path) - common_project_path = staticmethod(CloudBuildClient.common_project_path) - parse_common_project_path = staticmethod(CloudBuildClient.parse_common_project_path) - common_location_path = staticmethod(CloudBuildClient.common_location_path) - parse_common_location_path = staticmethod(CloudBuildClient.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: - CloudBuildAsyncClient: The constructed client. - """ - return CloudBuildClient.from_service_account_info.__func__(CloudBuildAsyncClient, 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: - CloudBuildAsyncClient: The constructed client. - """ - return CloudBuildClient.from_service_account_file.__func__(CloudBuildAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CloudBuildTransport: - """Returns the transport used by the client instance. - - Returns: - CloudBuildTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CloudBuildClient).get_transport_class, type(CloudBuildClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CloudBuildTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the cloud build 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, ~.CloudBuildTransport]): 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 = CloudBuildClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_build(self, - request: cloudbuild.CreateBuildRequest = None, - *, - project_id: str = None, - build: cloudbuild.Build = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts a build with the specified configuration. - - This method returns a long-running ``Operation``, which includes - the build ID. Pass the build ID to ``GetBuild`` to determine the - build status (such as ``SUCCESS`` or ``FAILURE``). - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.CreateBuildRequest`): - The request object. Request to create a new build. - project_id (:class:`str`): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - build (:class:`google.devtools.cloudbuild_v1.types.Build`): - Required. Build resource to create. - This corresponds to the ``build`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.devtools.cloudbuild_v1.types.Build` A - build resource in the Cloud Build API. - - At a high level, a Build describes where to find - source code, how to build it (for example, the - builder image to run on the source), and where to - store the built artifacts. - - Fields can include the following variables, which - will be expanded when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified - by RepoSource. - - $BRANCH_NAME: the branch name specified by - RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA - specified by RepoSource or resolved from the - specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or - $COMMIT_SHA. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, build]) - if request is 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 = cloudbuild.CreateBuildRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if build is not None: - request.build = build - - # 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_build, - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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, - cloudbuild.Build, - metadata_type=cloudbuild.BuildOperationMetadata, - ) - - # Done; return the response. - return response - - async def get_build(self, - request: cloudbuild.GetBuildRequest = None, - *, - project_id: str = None, - id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.Build: - r"""Returns information about a previously requested build. - - The ``Build`` that is returned includes its status (such as - ``SUCCESS``, ``FAILURE``, or ``WORKING``), and timing - information. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.GetBuildRequest`): - The request object. Request to get a build. - project_id (:class:`str`): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - id (:class:`str`): - Required. ID of the build. - This corresponds to the ``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.devtools.cloudbuild_v1.types.Build: - A build resource in the Cloud Build API. - - At a high level, a Build describes where to find - source code, how to build it (for example, the - builder image to run on the source), and where to - store the built artifacts. - - Fields can include the following variables, which - will be expanded when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified - by RepoSource. - - $BRANCH_NAME: the branch name specified by - RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA - specified by RepoSource or resolved from the - specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or - $COMMIT_SHA. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, 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 = cloudbuild.GetBuildRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if id is not None: - request.id = 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.get_build, - 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, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_builds(self, - request: cloudbuild.ListBuildsRequest = None, - *, - project_id: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListBuildsAsyncPager: - r"""Lists previously requested builds. - Previously requested builds may still be in-progress, or - may have finished successfully or unsuccessfully. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.ListBuildsRequest`): - The request object. Request to list builds. - project_id (:class:`str`): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The raw filter text to constrain the - results. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.devtools.cloudbuild_v1.services.cloud_build.pagers.ListBuildsAsyncPager: - Response including listed builds. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, filter]) - if request is 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 = cloudbuild.ListBuildsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if filter is not None: - request.filter = filter - - # 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_builds, - 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, - ) - - # 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.ListBuildsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def cancel_build(self, - request: cloudbuild.CancelBuildRequest = None, - *, - project_id: str = None, - id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.Build: - r"""Cancels a build in progress. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.CancelBuildRequest`): - The request object. Request to cancel an ongoing build. - project_id (:class:`str`): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - id (:class:`str`): - Required. ID of the build. - This corresponds to the ``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.devtools.cloudbuild_v1.types.Build: - A build resource in the Cloud Build API. - - At a high level, a Build describes where to find - source code, how to build it (for example, the - builder image to run on the source), and where to - store the built artifacts. - - Fields can include the following variables, which - will be expanded when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified - by RepoSource. - - $BRANCH_NAME: the branch name specified by - RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA - specified by RepoSource or resolved from the - specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or - $COMMIT_SHA. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, 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 = cloudbuild.CancelBuildRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if id is not None: - request.id = 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.cancel_build, - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def retry_build(self, - request: cloudbuild.RetryBuildRequest = None, - *, - project_id: str = None, - id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new build based on the specified build. - - This method creates a new build using the original build - request, which may or may not result in an identical build. - - For triggered builds: - - - Triggered builds resolve to a precise revision; therefore a - retry of a triggered build will result in a build that uses - the same revision. - - For non-triggered builds that specify ``RepoSource``: - - - If the original build built from the tip of a branch, the - retried build will build from the tip of that branch, which - may not be the same revision as the original build. - - If the original build specified a commit sha or revision ID, - the retried build will use the identical source. - - For builds that specify ``StorageSource``: - - - If the original build pulled source from Google Cloud Storage - without specifying the generation of the object, the new - build will use the current object, which may be different - from the original build source. - - If the original build pulled source from Cloud Storage and - specified the generation of the object, the new build will - attempt to use the same object, which may or may not be - available depending on the bucket's lifecycle management - settings. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.RetryBuildRequest`): - The request object. Specifies a build to retry. - project_id (:class:`str`): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - id (:class:`str`): - Required. Build ID of the original - build. - - This corresponds to the ``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.devtools.cloudbuild_v1.types.Build` A - build resource in the Cloud Build API. - - At a high level, a Build describes where to find - source code, how to build it (for example, the - builder image to run on the source), and where to - store the built artifacts. - - Fields can include the following variables, which - will be expanded when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified - by RepoSource. - - $BRANCH_NAME: the branch name specified by - RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA - specified by RepoSource or resolved from the - specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or - $COMMIT_SHA. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, 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 = cloudbuild.RetryBuildRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if id is not None: - request.id = 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.retry_build, - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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, - cloudbuild.Build, - metadata_type=cloudbuild.BuildOperationMetadata, - ) - - # Done; return the response. - return response - - async def create_build_trigger(self, - request: cloudbuild.CreateBuildTriggerRequest = None, - *, - project_id: str = None, - trigger: cloudbuild.BuildTrigger = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.BuildTrigger: - r"""Creates a new ``BuildTrigger``. - - This API is experimental. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.CreateBuildTriggerRequest`): - The request object. Request to create a new - `BuildTrigger`. - project_id (:class:`str`): - Required. ID of the project for which - to configure automatic builds. - - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger (:class:`google.devtools.cloudbuild_v1.types.BuildTrigger`): - Required. ``BuildTrigger`` to create. - This corresponds to the ``trigger`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.devtools.cloudbuild_v1.types.BuildTrigger: - Configuration for an automated build - in response to source repository - changes. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, trigger]) - if request is 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 = cloudbuild.CreateBuildTriggerRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if trigger is not None: - request.trigger = trigger - - # 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_build_trigger, - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_build_trigger(self, - request: cloudbuild.GetBuildTriggerRequest = None, - *, - project_id: str = None, - trigger_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.BuildTrigger: - r"""Returns information about a ``BuildTrigger``. - - This API is experimental. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.GetBuildTriggerRequest`): - The request object. Returns the `BuildTrigger` with the - specified ID. - project_id (:class:`str`): - Required. ID of the project that owns - the trigger. - - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger_id (:class:`str`): - Required. Identifier (``id`` or ``name``) of the - ``BuildTrigger`` to get. - - This corresponds to the ``trigger_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.devtools.cloudbuild_v1.types.BuildTrigger: - Configuration for an automated build - in response to source repository - changes. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, trigger_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 = cloudbuild.GetBuildTriggerRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if trigger_id is not None: - request.trigger_id = trigger_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.get_build_trigger, - 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, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_build_triggers(self, - request: cloudbuild.ListBuildTriggersRequest = None, - *, - project_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListBuildTriggersAsyncPager: - r"""Lists existing ``BuildTrigger``\ s. - - This API is experimental. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.ListBuildTriggersRequest`): - The request object. Request to list existing - `BuildTriggers`. - project_id (:class:`str`): - Required. ID of the project for which - to list BuildTriggers. - - This corresponds to the ``project_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.devtools.cloudbuild_v1.services.cloud_build.pagers.ListBuildTriggersAsyncPager: - Response containing existing BuildTriggers. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_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 = cloudbuild.ListBuildTriggersRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_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.list_build_triggers, - 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, - ) - - # 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.ListBuildTriggersAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_build_trigger(self, - request: cloudbuild.DeleteBuildTriggerRequest = None, - *, - project_id: str = None, - trigger_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ``BuildTrigger`` by its project ID and trigger ID. - - This API is experimental. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.DeleteBuildTriggerRequest`): - The request object. Request to delete a `BuildTrigger`. - project_id (:class:`str`): - Required. ID of the project that owns - the trigger. - - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger_id (:class:`str`): - Required. ID of the ``BuildTrigger`` to delete. - This corresponds to the ``trigger_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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, trigger_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 = cloudbuild.DeleteBuildTriggerRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if trigger_id is not None: - request.trigger_id = trigger_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.delete_build_trigger, - 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, - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_build_trigger(self, - request: cloudbuild.UpdateBuildTriggerRequest = None, - *, - project_id: str = None, - trigger_id: str = None, - trigger: cloudbuild.BuildTrigger = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.BuildTrigger: - r"""Updates a ``BuildTrigger`` by its project ID and trigger ID. - - This API is experimental. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.UpdateBuildTriggerRequest`): - The request object. Request to update an existing - `BuildTrigger`. - project_id (:class:`str`): - Required. ID of the project that owns - the trigger. - - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger_id (:class:`str`): - Required. ID of the ``BuildTrigger`` to update. - This corresponds to the ``trigger_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger (:class:`google.devtools.cloudbuild_v1.types.BuildTrigger`): - Required. ``BuildTrigger`` to update. - This corresponds to the ``trigger`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.devtools.cloudbuild_v1.types.BuildTrigger: - Configuration for an automated build - in response to source repository - changes. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, trigger_id, trigger]) - if request is 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 = cloudbuild.UpdateBuildTriggerRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if trigger_id is not None: - request.trigger_id = trigger_id - if trigger is not None: - request.trigger = trigger - - # 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_build_trigger, - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_build_trigger(self, - request: cloudbuild.RunBuildTriggerRequest = None, - *, - project_id: str = None, - trigger_id: str = None, - source: cloudbuild.RepoSource = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs a ``BuildTrigger`` at a particular source revision. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.RunBuildTriggerRequest`): - The request object. Specifies a build trigger to run and - the source to use. - project_id (:class:`str`): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger_id (:class:`str`): - Required. ID of the trigger. - This corresponds to the ``trigger_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.devtools.cloudbuild_v1.types.RepoSource`): - Source to build against this trigger. - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.devtools.cloudbuild_v1.types.Build` A - build resource in the Cloud Build API. - - At a high level, a Build describes where to find - source code, how to build it (for example, the - builder image to run on the source), and where to - store the built artifacts. - - Fields can include the following variables, which - will be expanded when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified - by RepoSource. - - $BRANCH_NAME: the branch name specified by - RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA - specified by RepoSource or resolved from the - specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or - $COMMIT_SHA. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, trigger_id, source]) - if request is 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 = cloudbuild.RunBuildTriggerRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if trigger_id is not None: - request.trigger_id = trigger_id - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.run_build_trigger, - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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, - cloudbuild.Build, - metadata_type=cloudbuild.BuildOperationMetadata, - ) - - # Done; return the response. - return response - - async def receive_trigger_webhook(self, - request: cloudbuild.ReceiveTriggerWebhookRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.ReceiveTriggerWebhookResponse: - r"""ReceiveTriggerWebhook [Experimental] is called when the API - receives a webhook request targeted at a specific trigger. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.ReceiveTriggerWebhookRequest`): - The request object. ReceiveTriggerWebhookRequest - [Experimental] is the request object accepted by the - ReceiveTriggerWebhook 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.devtools.cloudbuild_v1.types.ReceiveTriggerWebhookResponse: - ReceiveTriggerWebhookResponse [Experimental] is the response object for the - ReceiveTriggerWebhook method. - - """ - # Create or coerce a protobuf request object. - request = cloudbuild.ReceiveTriggerWebhookRequest(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.receive_trigger_webhook, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_worker_pool(self, - request: cloudbuild.CreateWorkerPoolRequest = None, - *, - parent: str = None, - worker_pool: cloudbuild.WorkerPool = None, - worker_pool_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a ``WorkerPool``. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.CreateWorkerPoolRequest`): - The request object. Request to create a new - `WorkerPool`. - parent (:class:`str`): - Required. The parent resource where this worker pool - will be created. Format: - ``projects/{project}/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - worker_pool (:class:`google.devtools.cloudbuild_v1.types.WorkerPool`): - Required. ``WorkerPool`` resource to create. - This corresponds to the ``worker_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - worker_pool_id (:class:`str`): - Required. Immutable. The ID to use for the - ``WorkerPool``, which will become the final component of - the resource name. - - This value should be 1-63 characters, and valid - characters are /[a-z][0-9]-/. - - This corresponds to the ``worker_pool_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.devtools.cloudbuild_v1.types.WorkerPool` - Configuration for a WorkerPool. - - Cloud Build owns and maintains a pool of workers for - general use and have no access to a project's private - network. By default, builds submitted to Cloud Build - will use a worker from this pool. - - If your build needs access to resources on a private - network, create and use a WorkerPool to run your - builds. Private WorkerPools give your builds access - to any single VPC network that you administer, - including any on-prem resources connected to that VPC - network. For an overview of private pools, see - [Private pools - overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, worker_pool, worker_pool_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = cloudbuild.CreateWorkerPoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if worker_pool is not None: - request.worker_pool = worker_pool - if worker_pool_id is not None: - request.worker_pool_id = worker_pool_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_worker_pool, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - cloudbuild.WorkerPool, - metadata_type=cloudbuild.CreateWorkerPoolOperationMetadata, - ) - - # Done; return the response. - return response - - async def get_worker_pool(self, - request: cloudbuild.GetWorkerPoolRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.WorkerPool: - r"""Returns details of a ``WorkerPool``. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.GetWorkerPoolRequest`): - The request object. Request to get a `WorkerPool` with - the specified name. - name (:class:`str`): - Required. The name of the ``WorkerPool`` to retrieve. - Format: - ``projects/{project}/locations/{location}/workerPools/{workerPool}``. - - 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.devtools.cloudbuild_v1.types.WorkerPool: - Configuration for a WorkerPool. - - Cloud Build owns and maintains a pool of workers for - general use and have no access to a project's private - network. By default, builds submitted to Cloud Build - will use a worker from this pool. - - If your build needs access to resources on a private - network, create and use a WorkerPool to run your - builds. Private WorkerPools give your builds access - to any single VPC network that you administer, - including any on-prem resources connected to that VPC - network. For an overview of private pools, see - [Private pools - overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = cloudbuild.GetWorkerPoolRequest(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_worker_pool, - 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 delete_worker_pool(self, - request: cloudbuild.DeleteWorkerPoolRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a ``WorkerPool``. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.DeleteWorkerPoolRequest`): - The request object. Request to delete a `WorkerPool`. - name (:class:`str`): - Required. The name of the ``WorkerPool`` to delete. - Format: - ``projects/{project}/locations/{workerPool}/workerPools/{workerPool}``. - - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = cloudbuild.DeleteWorkerPoolRequest(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_worker_pool, - 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=cloudbuild.DeleteWorkerPoolOperationMetadata, - ) - - # Done; return the response. - return response - - async def update_worker_pool(self, - request: cloudbuild.UpdateWorkerPoolRequest = None, - *, - worker_pool: cloudbuild.WorkerPool = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates a ``WorkerPool``. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.UpdateWorkerPoolRequest`): - The request object. Request to update a `WorkerPool`. - worker_pool (:class:`google.devtools.cloudbuild_v1.types.WorkerPool`): - Required. The ``WorkerPool`` to update. - - The ``name`` field is used to identify the - ``WorkerPool`` to update. Format: - ``projects/{project}/locations/{location}/workerPools/{workerPool}``. - - This corresponds to the ``worker_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - A mask specifying which fields in ``worker_pool`` to - update. - - 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.devtools.cloudbuild_v1.types.WorkerPool` - Configuration for a WorkerPool. - - Cloud Build owns and maintains a pool of workers for - general use and have no access to a project's private - network. By default, builds submitted to Cloud Build - will use a worker from this pool. - - If your build needs access to resources on a private - network, create and use a WorkerPool to run your - builds. Private WorkerPools give your builds access - to any single VPC network that you administer, - including any on-prem resources connected to that VPC - network. For an overview of private pools, see - [Private pools - overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([worker_pool, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = cloudbuild.UpdateWorkerPoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if worker_pool is not None: - request.worker_pool = worker_pool - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_worker_pool, - 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(( - ("worker_pool.name", request.worker_pool.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, - cloudbuild.WorkerPool, - metadata_type=cloudbuild.UpdateWorkerPoolOperationMetadata, - ) - - # Done; return the response. - return response - - async def list_worker_pools(self, - request: cloudbuild.ListWorkerPoolsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkerPoolsAsyncPager: - r"""Lists ``WorkerPool``\ s. - - Args: - request (:class:`google.devtools.cloudbuild_v1.types.ListWorkerPoolsRequest`): - The request object. Request to list `WorkerPool`s. - parent (:class:`str`): - Required. The parent of the collection of - ``WorkerPools``. Format: - ``projects/{project}/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.devtools.cloudbuild_v1.services.cloud_build.pagers.ListWorkerPoolsAsyncPager: - Response containing existing WorkerPools. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = cloudbuild.ListWorkerPoolsRequest(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_worker_pools, - 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.ListWorkerPoolsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-devtools-cloudbuild", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CloudBuildAsyncClient", -) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/client.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/client.py deleted file mode 100644 index 841080f7..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/client.py +++ /dev/null @@ -1,2039 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.devtools.cloudbuild_v1.services.cloud_build import pagers -from google.devtools.cloudbuild_v1.types import cloudbuild -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CloudBuildTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CloudBuildGrpcTransport -from .transports.grpc_asyncio import CloudBuildGrpcAsyncIOTransport - - -class CloudBuildClientMeta(type): - """Metaclass for the CloudBuild 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[CloudBuildTransport]] - _transport_registry["grpc"] = CloudBuildGrpcTransport - _transport_registry["grpc_asyncio"] = CloudBuildGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CloudBuildTransport]: - """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 CloudBuildClient(metaclass=CloudBuildClientMeta): - """Creates and manages builds on Google Cloud Platform. - - The main concept used by this API is a ``Build``, which describes - the location of the source to build, how to build the source, and - where to store the built artifacts, if any. - - A user can list previously-requested builds or get builds by their - ID to determine the status of the build. - """ - - @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 = "cloudbuild.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: - CloudBuildClient: 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: - CloudBuildClient: 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) -> CloudBuildTransport: - """Returns the transport used by the client instance. - - Returns: - CloudBuildTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def build_path(project: str,build: str,) -> str: - """Returns a fully-qualified build string.""" - return "projects/{project}/builds/{build}".format(project=project, 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.+?)/builds/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def build_trigger_path(project: str,trigger: str,) -> str: - """Returns a fully-qualified build_trigger string.""" - return "projects/{project}/triggers/{trigger}".format(project=project, trigger=trigger, ) - - @staticmethod - def parse_build_trigger_path(path: str) -> Dict[str,str]: - """Parses a build_trigger path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/triggers/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def crypto_key_path(project: str,location: str,keyring: str,key: str,) -> str: - """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}".format(project=project, location=location, keyring=keyring, key=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 network_path(project: str,network: str,) -> str: - """Returns a fully-qualified network string.""" - return "projects/{project}/global/networks/{network}".format(project=project, network=network, ) - - @staticmethod - def parse_network_path(path: str) -> Dict[str,str]: - """Parses a network path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/global/networks/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def secret_version_path(project: str,secret: str,version: str,) -> str: - """Returns a fully-qualified secret_version string.""" - return "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) - - @staticmethod - def parse_secret_version_path(path: str) -> Dict[str,str]: - """Parses a secret_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_account_path(project: str,service_account: str,) -> str: - """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) - - @staticmethod - def parse_service_account_path(path: str) -> Dict[str,str]: - """Parses a service_account path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def subscription_path(project: str,subscription: str,) -> str: - """Returns a fully-qualified subscription string.""" - return "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) - - @staticmethod - def parse_subscription_path(path: str) -> Dict[str,str]: - """Parses a subscription path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/subscriptions/(?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 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CloudBuildTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the cloud build 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, CloudBuildTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CloudBuildTransport): - # transport is a CloudBuildTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def create_build(self, - request: cloudbuild.CreateBuildRequest = None, - *, - project_id: str = None, - build: cloudbuild.Build = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts a build with the specified configuration. - - This method returns a long-running ``Operation``, which includes - the build ID. Pass the build ID to ``GetBuild`` to determine the - build status (such as ``SUCCESS`` or ``FAILURE``). - - Args: - request (google.devtools.cloudbuild_v1.types.CreateBuildRequest): - The request object. Request to create a new build. - project_id (str): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - build (google.devtools.cloudbuild_v1.types.Build): - Required. Build resource to create. - This corresponds to the ``build`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.devtools.cloudbuild_v1.types.Build` A - build resource in the Cloud Build API. - - At a high level, a Build describes where to find - source code, how to build it (for example, the - builder image to run on the source), and where to - store the built artifacts. - - Fields can include the following variables, which - will be expanded when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified - by RepoSource. - - $BRANCH_NAME: the branch name specified by - RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA - specified by RepoSource or resolved from the - specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or - $COMMIT_SHA. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, build]) - if request is 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 cloudbuild.CreateBuildRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.CreateBuildRequest): - request = cloudbuild.CreateBuildRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if build is not None: - request.build = build - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_build] - - # 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, - cloudbuild.Build, - metadata_type=cloudbuild.BuildOperationMetadata, - ) - - # Done; return the response. - return response - - def get_build(self, - request: cloudbuild.GetBuildRequest = None, - *, - project_id: str = None, - id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.Build: - r"""Returns information about a previously requested build. - - The ``Build`` that is returned includes its status (such as - ``SUCCESS``, ``FAILURE``, or ``WORKING``), and timing - information. - - Args: - request (google.devtools.cloudbuild_v1.types.GetBuildRequest): - The request object. Request to get a build. - project_id (str): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - id (str): - Required. ID of the build. - This corresponds to the ``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.devtools.cloudbuild_v1.types.Build: - A build resource in the Cloud Build API. - - At a high level, a Build describes where to find - source code, how to build it (for example, the - builder image to run on the source), and where to - store the built artifacts. - - Fields can include the following variables, which - will be expanded when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified - by RepoSource. - - $BRANCH_NAME: the branch name specified by - RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA - specified by RepoSource or resolved from the - specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or - $COMMIT_SHA. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, 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 cloudbuild.GetBuildRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.GetBuildRequest): - request = cloudbuild.GetBuildRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if id is not None: - request.id = id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_build] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_builds(self, - request: cloudbuild.ListBuildsRequest = None, - *, - project_id: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListBuildsPager: - r"""Lists previously requested builds. - Previously requested builds may still be in-progress, or - may have finished successfully or unsuccessfully. - - Args: - request (google.devtools.cloudbuild_v1.types.ListBuildsRequest): - The request object. Request to list builds. - project_id (str): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The raw filter text to constrain the - results. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.devtools.cloudbuild_v1.services.cloud_build.pagers.ListBuildsPager: - Response including listed builds. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, filter]) - if request is 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 cloudbuild.ListBuildsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.ListBuildsRequest): - request = cloudbuild.ListBuildsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_builds] - - # 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.ListBuildsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def cancel_build(self, - request: cloudbuild.CancelBuildRequest = None, - *, - project_id: str = None, - id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.Build: - r"""Cancels a build in progress. - - Args: - request (google.devtools.cloudbuild_v1.types.CancelBuildRequest): - The request object. Request to cancel an ongoing build. - project_id (str): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - id (str): - Required. ID of the build. - This corresponds to the ``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.devtools.cloudbuild_v1.types.Build: - A build resource in the Cloud Build API. - - At a high level, a Build describes where to find - source code, how to build it (for example, the - builder image to run on the source), and where to - store the built artifacts. - - Fields can include the following variables, which - will be expanded when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified - by RepoSource. - - $BRANCH_NAME: the branch name specified by - RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA - specified by RepoSource or resolved from the - specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or - $COMMIT_SHA. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, 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 cloudbuild.CancelBuildRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.CancelBuildRequest): - request = cloudbuild.CancelBuildRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if id is not None: - request.id = id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.cancel_build] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def retry_build(self, - request: cloudbuild.RetryBuildRequest = None, - *, - project_id: str = None, - id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new build based on the specified build. - - This method creates a new build using the original build - request, which may or may not result in an identical build. - - For triggered builds: - - - Triggered builds resolve to a precise revision; therefore a - retry of a triggered build will result in a build that uses - the same revision. - - For non-triggered builds that specify ``RepoSource``: - - - If the original build built from the tip of a branch, the - retried build will build from the tip of that branch, which - may not be the same revision as the original build. - - If the original build specified a commit sha or revision ID, - the retried build will use the identical source. - - For builds that specify ``StorageSource``: - - - If the original build pulled source from Google Cloud Storage - without specifying the generation of the object, the new - build will use the current object, which may be different - from the original build source. - - If the original build pulled source from Cloud Storage and - specified the generation of the object, the new build will - attempt to use the same object, which may or may not be - available depending on the bucket's lifecycle management - settings. - - Args: - request (google.devtools.cloudbuild_v1.types.RetryBuildRequest): - The request object. Specifies a build to retry. - project_id (str): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - id (str): - Required. Build ID of the original - build. - - This corresponds to the ``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.devtools.cloudbuild_v1.types.Build` A - build resource in the Cloud Build API. - - At a high level, a Build describes where to find - source code, how to build it (for example, the - builder image to run on the source), and where to - store the built artifacts. - - Fields can include the following variables, which - will be expanded when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified - by RepoSource. - - $BRANCH_NAME: the branch name specified by - RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA - specified by RepoSource or resolved from the - specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or - $COMMIT_SHA. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, 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 cloudbuild.RetryBuildRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.RetryBuildRequest): - request = cloudbuild.RetryBuildRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if id is not None: - request.id = id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.retry_build] - - # 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, - cloudbuild.Build, - metadata_type=cloudbuild.BuildOperationMetadata, - ) - - # Done; return the response. - return response - - def create_build_trigger(self, - request: cloudbuild.CreateBuildTriggerRequest = None, - *, - project_id: str = None, - trigger: cloudbuild.BuildTrigger = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.BuildTrigger: - r"""Creates a new ``BuildTrigger``. - - This API is experimental. - - Args: - request (google.devtools.cloudbuild_v1.types.CreateBuildTriggerRequest): - The request object. Request to create a new - `BuildTrigger`. - project_id (str): - Required. ID of the project for which - to configure automatic builds. - - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger (google.devtools.cloudbuild_v1.types.BuildTrigger): - Required. ``BuildTrigger`` to create. - This corresponds to the ``trigger`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.devtools.cloudbuild_v1.types.BuildTrigger: - Configuration for an automated build - in response to source repository - changes. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, trigger]) - if request is 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 cloudbuild.CreateBuildTriggerRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.CreateBuildTriggerRequest): - request = cloudbuild.CreateBuildTriggerRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if trigger is not None: - request.trigger = trigger - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_build_trigger] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_build_trigger(self, - request: cloudbuild.GetBuildTriggerRequest = None, - *, - project_id: str = None, - trigger_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.BuildTrigger: - r"""Returns information about a ``BuildTrigger``. - - This API is experimental. - - Args: - request (google.devtools.cloudbuild_v1.types.GetBuildTriggerRequest): - The request object. Returns the `BuildTrigger` with the - specified ID. - project_id (str): - Required. ID of the project that owns - the trigger. - - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger_id (str): - Required. Identifier (``id`` or ``name``) of the - ``BuildTrigger`` to get. - - This corresponds to the ``trigger_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.devtools.cloudbuild_v1.types.BuildTrigger: - Configuration for an automated build - in response to source repository - changes. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, trigger_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 cloudbuild.GetBuildTriggerRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.GetBuildTriggerRequest): - request = cloudbuild.GetBuildTriggerRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if trigger_id is not None: - request.trigger_id = trigger_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_build_trigger] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_build_triggers(self, - request: cloudbuild.ListBuildTriggersRequest = None, - *, - project_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListBuildTriggersPager: - r"""Lists existing ``BuildTrigger``\ s. - - This API is experimental. - - Args: - request (google.devtools.cloudbuild_v1.types.ListBuildTriggersRequest): - The request object. Request to list existing - `BuildTriggers`. - project_id (str): - Required. ID of the project for which - to list BuildTriggers. - - This corresponds to the ``project_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.devtools.cloudbuild_v1.services.cloud_build.pagers.ListBuildTriggersPager: - Response containing existing BuildTriggers. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_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 cloudbuild.ListBuildTriggersRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.ListBuildTriggersRequest): - request = cloudbuild.ListBuildTriggersRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_build_triggers] - - # 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.ListBuildTriggersPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_build_trigger(self, - request: cloudbuild.DeleteBuildTriggerRequest = None, - *, - project_id: str = None, - trigger_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a ``BuildTrigger`` by its project ID and trigger ID. - - This API is experimental. - - Args: - request (google.devtools.cloudbuild_v1.types.DeleteBuildTriggerRequest): - The request object. Request to delete a `BuildTrigger`. - project_id (str): - Required. ID of the project that owns - the trigger. - - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger_id (str): - Required. ID of the ``BuildTrigger`` to delete. - This corresponds to the ``trigger_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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, trigger_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 cloudbuild.DeleteBuildTriggerRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.DeleteBuildTriggerRequest): - request = cloudbuild.DeleteBuildTriggerRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if trigger_id is not None: - request.trigger_id = trigger_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_build_trigger] - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_build_trigger(self, - request: cloudbuild.UpdateBuildTriggerRequest = None, - *, - project_id: str = None, - trigger_id: str = None, - trigger: cloudbuild.BuildTrigger = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.BuildTrigger: - r"""Updates a ``BuildTrigger`` by its project ID and trigger ID. - - This API is experimental. - - Args: - request (google.devtools.cloudbuild_v1.types.UpdateBuildTriggerRequest): - The request object. Request to update an existing - `BuildTrigger`. - project_id (str): - Required. ID of the project that owns - the trigger. - - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger_id (str): - Required. ID of the ``BuildTrigger`` to update. - This corresponds to the ``trigger_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger (google.devtools.cloudbuild_v1.types.BuildTrigger): - Required. ``BuildTrigger`` to update. - This corresponds to the ``trigger`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.devtools.cloudbuild_v1.types.BuildTrigger: - Configuration for an automated build - in response to source repository - changes. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, trigger_id, trigger]) - if request is 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 cloudbuild.UpdateBuildTriggerRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.UpdateBuildTriggerRequest): - request = cloudbuild.UpdateBuildTriggerRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if trigger_id is not None: - request.trigger_id = trigger_id - if trigger is not None: - request.trigger = trigger - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_build_trigger] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_build_trigger(self, - request: cloudbuild.RunBuildTriggerRequest = None, - *, - project_id: str = None, - trigger_id: str = None, - source: cloudbuild.RepoSource = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Runs a ``BuildTrigger`` at a particular source revision. - - Args: - request (google.devtools.cloudbuild_v1.types.RunBuildTriggerRequest): - The request object. Specifies a build trigger to run and - the source to use. - project_id (str): - Required. ID of the project. - This corresponds to the ``project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger_id (str): - Required. ID of the trigger. - This corresponds to the ``trigger_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.devtools.cloudbuild_v1.types.RepoSource): - Source to build against this trigger. - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.devtools.cloudbuild_v1.types.Build` A - build resource in the Cloud Build API. - - At a high level, a Build describes where to find - source code, how to build it (for example, the - builder image to run on the source), and where to - store the built artifacts. - - Fields can include the following variables, which - will be expanded when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified - by RepoSource. - - $BRANCH_NAME: the branch name specified by - RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA - specified by RepoSource or resolved from the - specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or - $COMMIT_SHA. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project_id, trigger_id, source]) - if request is 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 cloudbuild.RunBuildTriggerRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.RunBuildTriggerRequest): - request = cloudbuild.RunBuildTriggerRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project_id is not None: - request.project_id = project_id - if trigger_id is not None: - request.trigger_id = trigger_id - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_build_trigger] - - # 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, - cloudbuild.Build, - metadata_type=cloudbuild.BuildOperationMetadata, - ) - - # Done; return the response. - return response - - def receive_trigger_webhook(self, - request: cloudbuild.ReceiveTriggerWebhookRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.ReceiveTriggerWebhookResponse: - r"""ReceiveTriggerWebhook [Experimental] is called when the API - receives a webhook request targeted at a specific trigger. - - Args: - request (google.devtools.cloudbuild_v1.types.ReceiveTriggerWebhookRequest): - The request object. ReceiveTriggerWebhookRequest - [Experimental] is the request object accepted by the - ReceiveTriggerWebhook 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.devtools.cloudbuild_v1.types.ReceiveTriggerWebhookResponse: - ReceiveTriggerWebhookResponse [Experimental] is the response object for the - ReceiveTriggerWebhook method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a cloudbuild.ReceiveTriggerWebhookRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.ReceiveTriggerWebhookRequest): - request = cloudbuild.ReceiveTriggerWebhookRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.receive_trigger_webhook] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_worker_pool(self, - request: cloudbuild.CreateWorkerPoolRequest = None, - *, - parent: str = None, - worker_pool: cloudbuild.WorkerPool = None, - worker_pool_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a ``WorkerPool``. - - Args: - request (google.devtools.cloudbuild_v1.types.CreateWorkerPoolRequest): - The request object. Request to create a new - `WorkerPool`. - parent (str): - Required. The parent resource where this worker pool - will be created. Format: - ``projects/{project}/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - worker_pool (google.devtools.cloudbuild_v1.types.WorkerPool): - Required. ``WorkerPool`` resource to create. - This corresponds to the ``worker_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - worker_pool_id (str): - Required. Immutable. The ID to use for the - ``WorkerPool``, which will become the final component of - the resource name. - - This value should be 1-63 characters, and valid - characters are /[a-z][0-9]-/. - - This corresponds to the ``worker_pool_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.devtools.cloudbuild_v1.types.WorkerPool` - Configuration for a WorkerPool. - - Cloud Build owns and maintains a pool of workers for - general use and have no access to a project's private - network. By default, builds submitted to Cloud Build - will use a worker from this pool. - - If your build needs access to resources on a private - network, create and use a WorkerPool to run your - builds. Private WorkerPools give your builds access - to any single VPC network that you administer, - including any on-prem resources connected to that VPC - network. For an overview of private pools, see - [Private pools - overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, worker_pool, worker_pool_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a cloudbuild.CreateWorkerPoolRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.CreateWorkerPoolRequest): - request = cloudbuild.CreateWorkerPoolRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if worker_pool is not None: - request.worker_pool = worker_pool - if worker_pool_id is not None: - request.worker_pool_id = worker_pool_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_worker_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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, - cloudbuild.WorkerPool, - metadata_type=cloudbuild.CreateWorkerPoolOperationMetadata, - ) - - # Done; return the response. - return response - - def get_worker_pool(self, - request: cloudbuild.GetWorkerPoolRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> cloudbuild.WorkerPool: - r"""Returns details of a ``WorkerPool``. - - Args: - request (google.devtools.cloudbuild_v1.types.GetWorkerPoolRequest): - The request object. Request to get a `WorkerPool` with - the specified name. - name (str): - Required. The name of the ``WorkerPool`` to retrieve. - Format: - ``projects/{project}/locations/{location}/workerPools/{workerPool}``. - - 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.devtools.cloudbuild_v1.types.WorkerPool: - Configuration for a WorkerPool. - - Cloud Build owns and maintains a pool of workers for - general use and have no access to a project's private - network. By default, builds submitted to Cloud Build - will use a worker from this pool. - - If your build needs access to resources on a private - network, create and use a WorkerPool to run your - builds. Private WorkerPools give your builds access - to any single VPC network that you administer, - including any on-prem resources connected to that VPC - network. For an overview of private pools, see - [Private pools - overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a cloudbuild.GetWorkerPoolRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.GetWorkerPoolRequest): - request = cloudbuild.GetWorkerPoolRequest(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_worker_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_worker_pool(self, - request: cloudbuild.DeleteWorkerPoolRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a ``WorkerPool``. - - Args: - request (google.devtools.cloudbuild_v1.types.DeleteWorkerPoolRequest): - The request object. Request to delete a `WorkerPool`. - name (str): - Required. The name of the ``WorkerPool`` to delete. - Format: - ``projects/{project}/locations/{workerPool}/workerPools/{workerPool}``. - - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a cloudbuild.DeleteWorkerPoolRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.DeleteWorkerPoolRequest): - request = cloudbuild.DeleteWorkerPoolRequest(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_worker_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # 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=cloudbuild.DeleteWorkerPoolOperationMetadata, - ) - - # Done; return the response. - return response - - def update_worker_pool(self, - request: cloudbuild.UpdateWorkerPoolRequest = None, - *, - worker_pool: cloudbuild.WorkerPool = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates a ``WorkerPool``. - - Args: - request (google.devtools.cloudbuild_v1.types.UpdateWorkerPoolRequest): - The request object. Request to update a `WorkerPool`. - worker_pool (google.devtools.cloudbuild_v1.types.WorkerPool): - Required. The ``WorkerPool`` to update. - - The ``name`` field is used to identify the - ``WorkerPool`` to update. Format: - ``projects/{project}/locations/{location}/workerPools/{workerPool}``. - - This corresponds to the ``worker_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - A mask specifying which fields in ``worker_pool`` to - update. - - 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.devtools.cloudbuild_v1.types.WorkerPool` - Configuration for a WorkerPool. - - Cloud Build owns and maintains a pool of workers for - general use and have no access to a project's private - network. By default, builds submitted to Cloud Build - will use a worker from this pool. - - If your build needs access to resources on a private - network, create and use a WorkerPool to run your - builds. Private WorkerPools give your builds access - to any single VPC network that you administer, - including any on-prem resources connected to that VPC - network. For an overview of private pools, see - [Private pools - overview](\ https://cloud.google.com/build/docs/private-pools/private-pools-overview). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([worker_pool, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a cloudbuild.UpdateWorkerPoolRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.UpdateWorkerPoolRequest): - request = cloudbuild.UpdateWorkerPoolRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if worker_pool is not None: - request.worker_pool = worker_pool - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_worker_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("worker_pool.name", request.worker_pool.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, - cloudbuild.WorkerPool, - metadata_type=cloudbuild.UpdateWorkerPoolOperationMetadata, - ) - - # Done; return the response. - return response - - def list_worker_pools(self, - request: cloudbuild.ListWorkerPoolsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkerPoolsPager: - r"""Lists ``WorkerPool``\ s. - - Args: - request (google.devtools.cloudbuild_v1.types.ListWorkerPoolsRequest): - The request object. Request to list `WorkerPool`s. - parent (str): - Required. The parent of the collection of - ``WorkerPools``. Format: - ``projects/{project}/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.devtools.cloudbuild_v1.services.cloud_build.pagers.ListWorkerPoolsPager: - Response containing existing WorkerPools. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a cloudbuild.ListWorkerPoolsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, cloudbuild.ListWorkerPoolsRequest): - request = cloudbuild.ListWorkerPoolsRequest(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_worker_pools] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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.ListWorkerPoolsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-devtools-cloudbuild", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CloudBuildClient", -) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/pagers.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/pagers.py deleted file mode 100644 index c3ed5314..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/pagers.py +++ /dev/null @@ -1,384 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.devtools.cloudbuild_v1.types import cloudbuild - - -class ListBuildsPager: - """A pager for iterating through ``list_builds`` requests. - - This class thinly wraps an initial - :class:`google.devtools.cloudbuild_v1.types.ListBuildsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``builds`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListBuilds`` requests and continue to iterate - through the ``builds`` field on the - corresponding responses. - - All the usual :class:`google.devtools.cloudbuild_v1.types.ListBuildsResponse` - 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[..., cloudbuild.ListBuildsResponse], - request: cloudbuild.ListBuildsRequest, - response: cloudbuild.ListBuildsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.devtools.cloudbuild_v1.types.ListBuildsRequest): - The initial request object. - response (google.devtools.cloudbuild_v1.types.ListBuildsResponse): - 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 = cloudbuild.ListBuildsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[cloudbuild.ListBuildsResponse]: - 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) -> Iterable[cloudbuild.Build]: - for page in self.pages: - yield from page.builds - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBuildsAsyncPager: - """A pager for iterating through ``list_builds`` requests. - - This class thinly wraps an initial - :class:`google.devtools.cloudbuild_v1.types.ListBuildsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``builds`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListBuilds`` requests and continue to iterate - through the ``builds`` field on the - corresponding responses. - - All the usual :class:`google.devtools.cloudbuild_v1.types.ListBuildsResponse` - 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[cloudbuild.ListBuildsResponse]], - request: cloudbuild.ListBuildsRequest, - response: cloudbuild.ListBuildsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.devtools.cloudbuild_v1.types.ListBuildsRequest): - The initial request object. - response (google.devtools.cloudbuild_v1.types.ListBuildsResponse): - 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 = cloudbuild.ListBuildsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[cloudbuild.ListBuildsResponse]: - 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) -> AsyncIterable[cloudbuild.Build]: - async def async_generator(): - async for page in self.pages: - for response in page.builds: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBuildTriggersPager: - """A pager for iterating through ``list_build_triggers`` requests. - - This class thinly wraps an initial - :class:`google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``triggers`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListBuildTriggers`` requests and continue to iterate - through the ``triggers`` field on the - corresponding responses. - - All the usual :class:`google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse` - 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[..., cloudbuild.ListBuildTriggersResponse], - request: cloudbuild.ListBuildTriggersRequest, - response: cloudbuild.ListBuildTriggersResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.devtools.cloudbuild_v1.types.ListBuildTriggersRequest): - The initial request object. - response (google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse): - 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 = cloudbuild.ListBuildTriggersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[cloudbuild.ListBuildTriggersResponse]: - 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) -> Iterable[cloudbuild.BuildTrigger]: - for page in self.pages: - yield from page.triggers - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBuildTriggersAsyncPager: - """A pager for iterating through ``list_build_triggers`` requests. - - This class thinly wraps an initial - :class:`google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``triggers`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListBuildTriggers`` requests and continue to iterate - through the ``triggers`` field on the - corresponding responses. - - All the usual :class:`google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse` - 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[cloudbuild.ListBuildTriggersResponse]], - request: cloudbuild.ListBuildTriggersRequest, - response: cloudbuild.ListBuildTriggersResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.devtools.cloudbuild_v1.types.ListBuildTriggersRequest): - The initial request object. - response (google.devtools.cloudbuild_v1.types.ListBuildTriggersResponse): - 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 = cloudbuild.ListBuildTriggersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[cloudbuild.ListBuildTriggersResponse]: - 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) -> AsyncIterable[cloudbuild.BuildTrigger]: - async def async_generator(): - async for page in self.pages: - for response in page.triggers: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkerPoolsPager: - """A pager for iterating through ``list_worker_pools`` requests. - - This class thinly wraps an initial - :class:`google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``worker_pools`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkerPools`` requests and continue to iterate - through the ``worker_pools`` field on the - corresponding responses. - - All the usual :class:`google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse` - 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[..., cloudbuild.ListWorkerPoolsResponse], - request: cloudbuild.ListWorkerPoolsRequest, - response: cloudbuild.ListWorkerPoolsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.devtools.cloudbuild_v1.types.ListWorkerPoolsRequest): - The initial request object. - response (google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse): - 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 = cloudbuild.ListWorkerPoolsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[cloudbuild.ListWorkerPoolsResponse]: - 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) -> Iterable[cloudbuild.WorkerPool]: - for page in self.pages: - yield from page.worker_pools - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkerPoolsAsyncPager: - """A pager for iterating through ``list_worker_pools`` requests. - - This class thinly wraps an initial - :class:`google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``worker_pools`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkerPools`` requests and continue to iterate - through the ``worker_pools`` field on the - corresponding responses. - - All the usual :class:`google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse` - 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[cloudbuild.ListWorkerPoolsResponse]], - request: cloudbuild.ListWorkerPoolsRequest, - response: cloudbuild.ListWorkerPoolsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.devtools.cloudbuild_v1.types.ListWorkerPoolsRequest): - The initial request object. - response (google.devtools.cloudbuild_v1.types.ListWorkerPoolsResponse): - 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 = cloudbuild.ListWorkerPoolsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[cloudbuild.ListWorkerPoolsResponse]: - 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) -> AsyncIterable[cloudbuild.WorkerPool]: - async def async_generator(): - async for page in self.pages: - for response in page.worker_pools: - 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/devtools/cloudbuild_v1/services/cloud_build/transports/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/__init__.py deleted file mode 100644 index bc5e8ed5..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CloudBuildTransport -from .grpc import CloudBuildGrpcTransport -from .grpc_asyncio import CloudBuildGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CloudBuildTransport]] -_transport_registry['grpc'] = CloudBuildGrpcTransport -_transport_registry['grpc_asyncio'] = CloudBuildGrpcAsyncIOTransport - -__all__ = ( - 'CloudBuildTransport', - 'CloudBuildGrpcTransport', - 'CloudBuildGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/base.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/base.py deleted file mode 100644 index d62de80e..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/base.py +++ /dev/null @@ -1,449 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.devtools.cloudbuild_v1.types import cloudbuild -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-devtools-cloudbuild', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class CloudBuildTransport(abc.ABC): - """Abstract transport class for CloudBuild.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'cloudbuild.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_build: gapic_v1.method.wrap_method( - self.create_build, - default_timeout=600.0, - client_info=client_info, - ), - self.get_build: gapic_v1.method.wrap_method( - self.get_build, - 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.list_builds: gapic_v1.method.wrap_method( - self.list_builds, - 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.cancel_build: gapic_v1.method.wrap_method( - self.cancel_build, - default_timeout=600.0, - client_info=client_info, - ), - self.retry_build: gapic_v1.method.wrap_method( - self.retry_build, - default_timeout=600.0, - client_info=client_info, - ), - self.create_build_trigger: gapic_v1.method.wrap_method( - self.create_build_trigger, - default_timeout=600.0, - client_info=client_info, - ), - self.get_build_trigger: gapic_v1.method.wrap_method( - self.get_build_trigger, - 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.list_build_triggers: gapic_v1.method.wrap_method( - self.list_build_triggers, - 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_build_trigger: gapic_v1.method.wrap_method( - self.delete_build_trigger, - 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.update_build_trigger: gapic_v1.method.wrap_method( - self.update_build_trigger, - default_timeout=600.0, - client_info=client_info, - ), - self.run_build_trigger: gapic_v1.method.wrap_method( - self.run_build_trigger, - default_timeout=600.0, - client_info=client_info, - ), - self.receive_trigger_webhook: gapic_v1.method.wrap_method( - self.receive_trigger_webhook, - default_timeout=None, - client_info=client_info, - ), - self.create_worker_pool: gapic_v1.method.wrap_method( - self.create_worker_pool, - default_timeout=600.0, - client_info=client_info, - ), - self.get_worker_pool: gapic_v1.method.wrap_method( - self.get_worker_pool, - 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_worker_pool: gapic_v1.method.wrap_method( - self.delete_worker_pool, - default_timeout=600.0, - client_info=client_info, - ), - self.update_worker_pool: gapic_v1.method.wrap_method( - self.update_worker_pool, - default_timeout=600.0, - client_info=client_info, - ), - self.list_worker_pools: gapic_v1.method.wrap_method( - self.list_worker_pools, - 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, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_build(self) -> Callable[ - [cloudbuild.CreateBuildRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_build(self) -> Callable[ - [cloudbuild.GetBuildRequest], - Union[ - cloudbuild.Build, - Awaitable[cloudbuild.Build] - ]]: - raise NotImplementedError() - - @property - def list_builds(self) -> Callable[ - [cloudbuild.ListBuildsRequest], - Union[ - cloudbuild.ListBuildsResponse, - Awaitable[cloudbuild.ListBuildsResponse] - ]]: - raise NotImplementedError() - - @property - def cancel_build(self) -> Callable[ - [cloudbuild.CancelBuildRequest], - Union[ - cloudbuild.Build, - Awaitable[cloudbuild.Build] - ]]: - raise NotImplementedError() - - @property - def retry_build(self) -> Callable[ - [cloudbuild.RetryBuildRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_build_trigger(self) -> Callable[ - [cloudbuild.CreateBuildTriggerRequest], - Union[ - cloudbuild.BuildTrigger, - Awaitable[cloudbuild.BuildTrigger] - ]]: - raise NotImplementedError() - - @property - def get_build_trigger(self) -> Callable[ - [cloudbuild.GetBuildTriggerRequest], - Union[ - cloudbuild.BuildTrigger, - Awaitable[cloudbuild.BuildTrigger] - ]]: - raise NotImplementedError() - - @property - def list_build_triggers(self) -> Callable[ - [cloudbuild.ListBuildTriggersRequest], - Union[ - cloudbuild.ListBuildTriggersResponse, - Awaitable[cloudbuild.ListBuildTriggersResponse] - ]]: - raise NotImplementedError() - - @property - def delete_build_trigger(self) -> Callable[ - [cloudbuild.DeleteBuildTriggerRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_build_trigger(self) -> Callable[ - [cloudbuild.UpdateBuildTriggerRequest], - Union[ - cloudbuild.BuildTrigger, - Awaitable[cloudbuild.BuildTrigger] - ]]: - raise NotImplementedError() - - @property - def run_build_trigger(self) -> Callable[ - [cloudbuild.RunBuildTriggerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def receive_trigger_webhook(self) -> Callable[ - [cloudbuild.ReceiveTriggerWebhookRequest], - Union[ - cloudbuild.ReceiveTriggerWebhookResponse, - Awaitable[cloudbuild.ReceiveTriggerWebhookResponse] - ]]: - raise NotImplementedError() - - @property - def create_worker_pool(self) -> Callable[ - [cloudbuild.CreateWorkerPoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_worker_pool(self) -> Callable[ - [cloudbuild.GetWorkerPoolRequest], - Union[ - cloudbuild.WorkerPool, - Awaitable[cloudbuild.WorkerPool] - ]]: - raise NotImplementedError() - - @property - def delete_worker_pool(self) -> Callable[ - [cloudbuild.DeleteWorkerPoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_worker_pool(self) -> Callable[ - [cloudbuild.UpdateWorkerPoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_worker_pools(self) -> Callable[ - [cloudbuild.ListWorkerPoolsRequest], - Union[ - cloudbuild.ListWorkerPoolsResponse, - Awaitable[cloudbuild.ListWorkerPoolsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'CloudBuildTransport', -) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc.py deleted file mode 100644 index 70a55a7f..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc.py +++ /dev/null @@ -1,745 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.devtools.cloudbuild_v1.types import cloudbuild -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import CloudBuildTransport, DEFAULT_CLIENT_INFO - - -class CloudBuildGrpcTransport(CloudBuildTransport): - """gRPC backend transport for CloudBuild. - - Creates and manages builds on Google Cloud Platform. - - The main concept used by this API is a ``Build``, which describes - the location of the source to build, how to build the source, and - where to store the built artifacts, if any. - - A user can list previously-requested builds or get builds by their - ID to determine the status of the build. - - 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 = 'cloudbuild.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin 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 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 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 = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudbuild.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. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_build(self) -> Callable[ - [cloudbuild.CreateBuildRequest], - operations_pb2.Operation]: - r"""Return a callable for the create build method over gRPC. - - Starts a build with the specified configuration. - - This method returns a long-running ``Operation``, which includes - the build ID. Pass the build ID to ``GetBuild`` to determine the - build status (such as ``SUCCESS`` or ``FAILURE``). - - Returns: - Callable[[~.CreateBuildRequest], - ~.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_build' not in self._stubs: - self._stubs['create_build'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/CreateBuild', - request_serializer=cloudbuild.CreateBuildRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_build'] - - @property - def get_build(self) -> Callable[ - [cloudbuild.GetBuildRequest], - cloudbuild.Build]: - r"""Return a callable for the get build method over gRPC. - - Returns information about a previously requested build. - - The ``Build`` that is returned includes its status (such as - ``SUCCESS``, ``FAILURE``, or ``WORKING``), and timing - information. - - Returns: - Callable[[~.GetBuildRequest], - ~.Build]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_build' not in self._stubs: - self._stubs['get_build'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/GetBuild', - request_serializer=cloudbuild.GetBuildRequest.serialize, - response_deserializer=cloudbuild.Build.deserialize, - ) - return self._stubs['get_build'] - - @property - def list_builds(self) -> Callable[ - [cloudbuild.ListBuildsRequest], - cloudbuild.ListBuildsResponse]: - r"""Return a callable for the list builds method over gRPC. - - Lists previously requested builds. - Previously requested builds may still be in-progress, or - may have finished successfully or unsuccessfully. - - Returns: - Callable[[~.ListBuildsRequest], - ~.ListBuildsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_builds' not in self._stubs: - self._stubs['list_builds'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/ListBuilds', - request_serializer=cloudbuild.ListBuildsRequest.serialize, - response_deserializer=cloudbuild.ListBuildsResponse.deserialize, - ) - return self._stubs['list_builds'] - - @property - def cancel_build(self) -> Callable[ - [cloudbuild.CancelBuildRequest], - cloudbuild.Build]: - r"""Return a callable for the cancel build method over gRPC. - - Cancels a build in progress. - - Returns: - Callable[[~.CancelBuildRequest], - ~.Build]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'cancel_build' not in self._stubs: - self._stubs['cancel_build'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/CancelBuild', - request_serializer=cloudbuild.CancelBuildRequest.serialize, - response_deserializer=cloudbuild.Build.deserialize, - ) - return self._stubs['cancel_build'] - - @property - def retry_build(self) -> Callable[ - [cloudbuild.RetryBuildRequest], - operations_pb2.Operation]: - r"""Return a callable for the retry build method over gRPC. - - Creates a new build based on the specified build. - - This method creates a new build using the original build - request, which may or may not result in an identical build. - - For triggered builds: - - - Triggered builds resolve to a precise revision; therefore a - retry of a triggered build will result in a build that uses - the same revision. - - For non-triggered builds that specify ``RepoSource``: - - - If the original build built from the tip of a branch, the - retried build will build from the tip of that branch, which - may not be the same revision as the original build. - - If the original build specified a commit sha or revision ID, - the retried build will use the identical source. - - For builds that specify ``StorageSource``: - - - If the original build pulled source from Google Cloud Storage - without specifying the generation of the object, the new - build will use the current object, which may be different - from the original build source. - - If the original build pulled source from Cloud Storage and - specified the generation of the object, the new build will - attempt to use the same object, which may or may not be - available depending on the bucket's lifecycle management - settings. - - Returns: - Callable[[~.RetryBuildRequest], - ~.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 'retry_build' not in self._stubs: - self._stubs['retry_build'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/RetryBuild', - request_serializer=cloudbuild.RetryBuildRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['retry_build'] - - @property - def create_build_trigger(self) -> Callable[ - [cloudbuild.CreateBuildTriggerRequest], - cloudbuild.BuildTrigger]: - r"""Return a callable for the create build trigger method over gRPC. - - Creates a new ``BuildTrigger``. - - This API is experimental. - - Returns: - Callable[[~.CreateBuildTriggerRequest], - ~.BuildTrigger]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: - self._stubs['create_build_trigger'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/CreateBuildTrigger', - request_serializer=cloudbuild.CreateBuildTriggerRequest.serialize, - response_deserializer=cloudbuild.BuildTrigger.deserialize, - ) - return self._stubs['create_build_trigger'] - - @property - def get_build_trigger(self) -> Callable[ - [cloudbuild.GetBuildTriggerRequest], - cloudbuild.BuildTrigger]: - r"""Return a callable for the get build trigger method over gRPC. - - Returns information about a ``BuildTrigger``. - - This API is experimental. - - Returns: - Callable[[~.GetBuildTriggerRequest], - ~.BuildTrigger]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: - self._stubs['get_build_trigger'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/GetBuildTrigger', - request_serializer=cloudbuild.GetBuildTriggerRequest.serialize, - response_deserializer=cloudbuild.BuildTrigger.deserialize, - ) - return self._stubs['get_build_trigger'] - - @property - def list_build_triggers(self) -> Callable[ - [cloudbuild.ListBuildTriggersRequest], - cloudbuild.ListBuildTriggersResponse]: - r"""Return a callable for the list build triggers method over gRPC. - - Lists existing ``BuildTrigger``\ s. - - This API is experimental. - - Returns: - Callable[[~.ListBuildTriggersRequest], - ~.ListBuildTriggersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_build_triggers' not in self._stubs: - self._stubs['list_build_triggers'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/ListBuildTriggers', - request_serializer=cloudbuild.ListBuildTriggersRequest.serialize, - response_deserializer=cloudbuild.ListBuildTriggersResponse.deserialize, - ) - return self._stubs['list_build_triggers'] - - @property - def delete_build_trigger(self) -> Callable[ - [cloudbuild.DeleteBuildTriggerRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete build trigger method over gRPC. - - Deletes a ``BuildTrigger`` by its project ID and trigger ID. - - This API is experimental. - - Returns: - Callable[[~.DeleteBuildTriggerRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_build_trigger' not in self._stubs: - self._stubs['delete_build_trigger'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/DeleteBuildTrigger', - request_serializer=cloudbuild.DeleteBuildTriggerRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_build_trigger'] - - @property - def update_build_trigger(self) -> Callable[ - [cloudbuild.UpdateBuildTriggerRequest], - cloudbuild.BuildTrigger]: - r"""Return a callable for the update build trigger method over gRPC. - - Updates a ``BuildTrigger`` by its project ID and trigger ID. - - This API is experimental. - - Returns: - Callable[[~.UpdateBuildTriggerRequest], - ~.BuildTrigger]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: - self._stubs['update_build_trigger'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/UpdateBuildTrigger', - request_serializer=cloudbuild.UpdateBuildTriggerRequest.serialize, - response_deserializer=cloudbuild.BuildTrigger.deserialize, - ) - return self._stubs['update_build_trigger'] - - @property - def run_build_trigger(self) -> Callable[ - [cloudbuild.RunBuildTriggerRequest], - operations_pb2.Operation]: - r"""Return a callable for the run build trigger method over gRPC. - - Runs a ``BuildTrigger`` at a particular source revision. - - Returns: - Callable[[~.RunBuildTriggerRequest], - ~.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 'run_build_trigger' not in self._stubs: - self._stubs['run_build_trigger'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/RunBuildTrigger', - request_serializer=cloudbuild.RunBuildTriggerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_build_trigger'] - - @property - def receive_trigger_webhook(self) -> Callable[ - [cloudbuild.ReceiveTriggerWebhookRequest], - cloudbuild.ReceiveTriggerWebhookResponse]: - r"""Return a callable for the receive trigger webhook method over gRPC. - - ReceiveTriggerWebhook [Experimental] is called when the API - receives a webhook request targeted at a specific trigger. - - Returns: - Callable[[~.ReceiveTriggerWebhookRequest], - ~.ReceiveTriggerWebhookResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'receive_trigger_webhook' not in self._stubs: - self._stubs['receive_trigger_webhook'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/ReceiveTriggerWebhook', - request_serializer=cloudbuild.ReceiveTriggerWebhookRequest.serialize, - response_deserializer=cloudbuild.ReceiveTriggerWebhookResponse.deserialize, - ) - return self._stubs['receive_trigger_webhook'] - - @property - def create_worker_pool(self) -> Callable[ - [cloudbuild.CreateWorkerPoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the create worker pool method over gRPC. - - Creates a ``WorkerPool``. - - Returns: - Callable[[~.CreateWorkerPoolRequest], - ~.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_worker_pool' not in self._stubs: - self._stubs['create_worker_pool'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/CreateWorkerPool', - request_serializer=cloudbuild.CreateWorkerPoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_worker_pool'] - - @property - def get_worker_pool(self) -> Callable[ - [cloudbuild.GetWorkerPoolRequest], - cloudbuild.WorkerPool]: - r"""Return a callable for the get worker pool method over gRPC. - - Returns details of a ``WorkerPool``. - - Returns: - Callable[[~.GetWorkerPoolRequest], - ~.WorkerPool]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_worker_pool' not in self._stubs: - self._stubs['get_worker_pool'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/GetWorkerPool', - request_serializer=cloudbuild.GetWorkerPoolRequest.serialize, - response_deserializer=cloudbuild.WorkerPool.deserialize, - ) - return self._stubs['get_worker_pool'] - - @property - def delete_worker_pool(self) -> Callable[ - [cloudbuild.DeleteWorkerPoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete worker pool method over gRPC. - - Deletes a ``WorkerPool``. - - Returns: - Callable[[~.DeleteWorkerPoolRequest], - ~.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_worker_pool' not in self._stubs: - self._stubs['delete_worker_pool'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/DeleteWorkerPool', - request_serializer=cloudbuild.DeleteWorkerPoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_worker_pool'] - - @property - def update_worker_pool(self) -> Callable[ - [cloudbuild.UpdateWorkerPoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the update worker pool method over gRPC. - - Updates a ``WorkerPool``. - - Returns: - Callable[[~.UpdateWorkerPoolRequest], - ~.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_worker_pool' not in self._stubs: - self._stubs['update_worker_pool'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/UpdateWorkerPool', - request_serializer=cloudbuild.UpdateWorkerPoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_worker_pool'] - - @property - def list_worker_pools(self) -> Callable[ - [cloudbuild.ListWorkerPoolsRequest], - cloudbuild.ListWorkerPoolsResponse]: - r"""Return a callable for the list worker pools method over gRPC. - - Lists ``WorkerPool``\ s. - - Returns: - Callable[[~.ListWorkerPoolsRequest], - ~.ListWorkerPoolsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_worker_pools' not in self._stubs: - self._stubs['list_worker_pools'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/ListWorkerPools', - request_serializer=cloudbuild.ListWorkerPoolsRequest.serialize, - response_deserializer=cloudbuild.ListWorkerPoolsResponse.deserialize, - ) - return self._stubs['list_worker_pools'] - - -__all__ = ( - 'CloudBuildGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc_asyncio.py deleted file mode 100644 index b1f3a881..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/services/cloud_build/transports/grpc_asyncio.py +++ /dev/null @@ -1,749 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.devtools.cloudbuild_v1.types import cloudbuild -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import CloudBuildTransport, DEFAULT_CLIENT_INFO -from .grpc import CloudBuildGrpcTransport - - -class CloudBuildGrpcAsyncIOTransport(CloudBuildTransport): - """gRPC AsyncIO backend transport for CloudBuild. - - Creates and manages builds on Google Cloud Platform. - - The main concept used by this API is a ``Build``, which describes - the location of the source to build, how to build the source, and - where to store the built artifacts, if any. - - A user can list previously-requested builds or get builds by their - ID to determine the status of the build. - - 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 = 'cloudbuild.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 = 'cloudbuild.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin 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 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 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 = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_build(self) -> Callable[ - [cloudbuild.CreateBuildRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create build method over gRPC. - - Starts a build with the specified configuration. - - This method returns a long-running ``Operation``, which includes - the build ID. Pass the build ID to ``GetBuild`` to determine the - build status (such as ``SUCCESS`` or ``FAILURE``). - - Returns: - Callable[[~.CreateBuildRequest], - 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_build' not in self._stubs: - self._stubs['create_build'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/CreateBuild', - request_serializer=cloudbuild.CreateBuildRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_build'] - - @property - def get_build(self) -> Callable[ - [cloudbuild.GetBuildRequest], - Awaitable[cloudbuild.Build]]: - r"""Return a callable for the get build method over gRPC. - - Returns information about a previously requested build. - - The ``Build`` that is returned includes its status (such as - ``SUCCESS``, ``FAILURE``, or ``WORKING``), and timing - information. - - Returns: - Callable[[~.GetBuildRequest], - Awaitable[~.Build]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_build' not in self._stubs: - self._stubs['get_build'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/GetBuild', - request_serializer=cloudbuild.GetBuildRequest.serialize, - response_deserializer=cloudbuild.Build.deserialize, - ) - return self._stubs['get_build'] - - @property - def list_builds(self) -> Callable[ - [cloudbuild.ListBuildsRequest], - Awaitable[cloudbuild.ListBuildsResponse]]: - r"""Return a callable for the list builds method over gRPC. - - Lists previously requested builds. - Previously requested builds may still be in-progress, or - may have finished successfully or unsuccessfully. - - Returns: - Callable[[~.ListBuildsRequest], - Awaitable[~.ListBuildsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_builds' not in self._stubs: - self._stubs['list_builds'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/ListBuilds', - request_serializer=cloudbuild.ListBuildsRequest.serialize, - response_deserializer=cloudbuild.ListBuildsResponse.deserialize, - ) - return self._stubs['list_builds'] - - @property - def cancel_build(self) -> Callable[ - [cloudbuild.CancelBuildRequest], - Awaitable[cloudbuild.Build]]: - r"""Return a callable for the cancel build method over gRPC. - - Cancels a build in progress. - - Returns: - Callable[[~.CancelBuildRequest], - Awaitable[~.Build]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'cancel_build' not in self._stubs: - self._stubs['cancel_build'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/CancelBuild', - request_serializer=cloudbuild.CancelBuildRequest.serialize, - response_deserializer=cloudbuild.Build.deserialize, - ) - return self._stubs['cancel_build'] - - @property - def retry_build(self) -> Callable[ - [cloudbuild.RetryBuildRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the retry build method over gRPC. - - Creates a new build based on the specified build. - - This method creates a new build using the original build - request, which may or may not result in an identical build. - - For triggered builds: - - - Triggered builds resolve to a precise revision; therefore a - retry of a triggered build will result in a build that uses - the same revision. - - For non-triggered builds that specify ``RepoSource``: - - - If the original build built from the tip of a branch, the - retried build will build from the tip of that branch, which - may not be the same revision as the original build. - - If the original build specified a commit sha or revision ID, - the retried build will use the identical source. - - For builds that specify ``StorageSource``: - - - If the original build pulled source from Google Cloud Storage - without specifying the generation of the object, the new - build will use the current object, which may be different - from the original build source. - - If the original build pulled source from Cloud Storage and - specified the generation of the object, the new build will - attempt to use the same object, which may or may not be - available depending on the bucket's lifecycle management - settings. - - Returns: - Callable[[~.RetryBuildRequest], - 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 'retry_build' not in self._stubs: - self._stubs['retry_build'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/RetryBuild', - request_serializer=cloudbuild.RetryBuildRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['retry_build'] - - @property - def create_build_trigger(self) -> Callable[ - [cloudbuild.CreateBuildTriggerRequest], - Awaitable[cloudbuild.BuildTrigger]]: - r"""Return a callable for the create build trigger method over gRPC. - - Creates a new ``BuildTrigger``. - - This API is experimental. - - Returns: - Callable[[~.CreateBuildTriggerRequest], - Awaitable[~.BuildTrigger]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: - self._stubs['create_build_trigger'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/CreateBuildTrigger', - request_serializer=cloudbuild.CreateBuildTriggerRequest.serialize, - response_deserializer=cloudbuild.BuildTrigger.deserialize, - ) - return self._stubs['create_build_trigger'] - - @property - def get_build_trigger(self) -> Callable[ - [cloudbuild.GetBuildTriggerRequest], - Awaitable[cloudbuild.BuildTrigger]]: - r"""Return a callable for the get build trigger method over gRPC. - - Returns information about a ``BuildTrigger``. - - This API is experimental. - - Returns: - Callable[[~.GetBuildTriggerRequest], - Awaitable[~.BuildTrigger]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: - self._stubs['get_build_trigger'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/GetBuildTrigger', - request_serializer=cloudbuild.GetBuildTriggerRequest.serialize, - response_deserializer=cloudbuild.BuildTrigger.deserialize, - ) - return self._stubs['get_build_trigger'] - - @property - def list_build_triggers(self) -> Callable[ - [cloudbuild.ListBuildTriggersRequest], - Awaitable[cloudbuild.ListBuildTriggersResponse]]: - r"""Return a callable for the list build triggers method over gRPC. - - Lists existing ``BuildTrigger``\ s. - - This API is experimental. - - Returns: - Callable[[~.ListBuildTriggersRequest], - Awaitable[~.ListBuildTriggersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_build_triggers' not in self._stubs: - self._stubs['list_build_triggers'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/ListBuildTriggers', - request_serializer=cloudbuild.ListBuildTriggersRequest.serialize, - response_deserializer=cloudbuild.ListBuildTriggersResponse.deserialize, - ) - return self._stubs['list_build_triggers'] - - @property - def delete_build_trigger(self) -> Callable[ - [cloudbuild.DeleteBuildTriggerRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete build trigger method over gRPC. - - Deletes a ``BuildTrigger`` by its project ID and trigger ID. - - This API is experimental. - - Returns: - Callable[[~.DeleteBuildTriggerRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_build_trigger' not in self._stubs: - self._stubs['delete_build_trigger'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/DeleteBuildTrigger', - request_serializer=cloudbuild.DeleteBuildTriggerRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_build_trigger'] - - @property - def update_build_trigger(self) -> Callable[ - [cloudbuild.UpdateBuildTriggerRequest], - Awaitable[cloudbuild.BuildTrigger]]: - r"""Return a callable for the update build trigger method over gRPC. - - Updates a ``BuildTrigger`` by its project ID and trigger ID. - - This API is experimental. - - Returns: - Callable[[~.UpdateBuildTriggerRequest], - Awaitable[~.BuildTrigger]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_build_trigger' not in self._stubs: - self._stubs['update_build_trigger'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/UpdateBuildTrigger', - request_serializer=cloudbuild.UpdateBuildTriggerRequest.serialize, - response_deserializer=cloudbuild.BuildTrigger.deserialize, - ) - return self._stubs['update_build_trigger'] - - @property - def run_build_trigger(self) -> Callable[ - [cloudbuild.RunBuildTriggerRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run build trigger method over gRPC. - - Runs a ``BuildTrigger`` at a particular source revision. - - Returns: - Callable[[~.RunBuildTriggerRequest], - 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 'run_build_trigger' not in self._stubs: - self._stubs['run_build_trigger'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/RunBuildTrigger', - request_serializer=cloudbuild.RunBuildTriggerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_build_trigger'] - - @property - def receive_trigger_webhook(self) -> Callable[ - [cloudbuild.ReceiveTriggerWebhookRequest], - Awaitable[cloudbuild.ReceiveTriggerWebhookResponse]]: - r"""Return a callable for the receive trigger webhook method over gRPC. - - ReceiveTriggerWebhook [Experimental] is called when the API - receives a webhook request targeted at a specific trigger. - - Returns: - Callable[[~.ReceiveTriggerWebhookRequest], - Awaitable[~.ReceiveTriggerWebhookResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'receive_trigger_webhook' not in self._stubs: - self._stubs['receive_trigger_webhook'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/ReceiveTriggerWebhook', - request_serializer=cloudbuild.ReceiveTriggerWebhookRequest.serialize, - response_deserializer=cloudbuild.ReceiveTriggerWebhookResponse.deserialize, - ) - return self._stubs['receive_trigger_webhook'] - - @property - def create_worker_pool(self) -> Callable[ - [cloudbuild.CreateWorkerPoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create worker pool method over gRPC. - - Creates a ``WorkerPool``. - - Returns: - Callable[[~.CreateWorkerPoolRequest], - 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_worker_pool' not in self._stubs: - self._stubs['create_worker_pool'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/CreateWorkerPool', - request_serializer=cloudbuild.CreateWorkerPoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_worker_pool'] - - @property - def get_worker_pool(self) -> Callable[ - [cloudbuild.GetWorkerPoolRequest], - Awaitable[cloudbuild.WorkerPool]]: - r"""Return a callable for the get worker pool method over gRPC. - - Returns details of a ``WorkerPool``. - - Returns: - Callable[[~.GetWorkerPoolRequest], - Awaitable[~.WorkerPool]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_worker_pool' not in self._stubs: - self._stubs['get_worker_pool'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/GetWorkerPool', - request_serializer=cloudbuild.GetWorkerPoolRequest.serialize, - response_deserializer=cloudbuild.WorkerPool.deserialize, - ) - return self._stubs['get_worker_pool'] - - @property - def delete_worker_pool(self) -> Callable[ - [cloudbuild.DeleteWorkerPoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete worker pool method over gRPC. - - Deletes a ``WorkerPool``. - - Returns: - Callable[[~.DeleteWorkerPoolRequest], - 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_worker_pool' not in self._stubs: - self._stubs['delete_worker_pool'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/DeleteWorkerPool', - request_serializer=cloudbuild.DeleteWorkerPoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_worker_pool'] - - @property - def update_worker_pool(self) -> Callable[ - [cloudbuild.UpdateWorkerPoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update worker pool method over gRPC. - - Updates a ``WorkerPool``. - - Returns: - Callable[[~.UpdateWorkerPoolRequest], - 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_worker_pool' not in self._stubs: - self._stubs['update_worker_pool'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/UpdateWorkerPool', - request_serializer=cloudbuild.UpdateWorkerPoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_worker_pool'] - - @property - def list_worker_pools(self) -> Callable[ - [cloudbuild.ListWorkerPoolsRequest], - Awaitable[cloudbuild.ListWorkerPoolsResponse]]: - r"""Return a callable for the list worker pools method over gRPC. - - Lists ``WorkerPool``\ s. - - Returns: - Callable[[~.ListWorkerPoolsRequest], - Awaitable[~.ListWorkerPoolsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_worker_pools' not in self._stubs: - self._stubs['list_worker_pools'] = self.grpc_channel.unary_unary( - '/google.devtools.cloudbuild.v1.CloudBuild/ListWorkerPools', - request_serializer=cloudbuild.ListWorkerPoolsRequest.serialize, - response_deserializer=cloudbuild.ListWorkerPoolsResponse.deserialize, - ) - return self._stubs['list_worker_pools'] - - -__all__ = ( - 'CloudBuildGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/__init__.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/__init__.py deleted file mode 100644 index b09050ee..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/__init__.py +++ /dev/null @@ -1,126 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .cloudbuild import ( - ArtifactResult, - Artifacts, - Build, - BuildOperationMetadata, - BuildOptions, - BuildStep, - BuildTrigger, - BuiltImage, - CancelBuildRequest, - CreateBuildRequest, - CreateBuildTriggerRequest, - CreateWorkerPoolOperationMetadata, - CreateWorkerPoolRequest, - DeleteBuildTriggerRequest, - DeleteWorkerPoolOperationMetadata, - DeleteWorkerPoolRequest, - FileHashes, - GetBuildRequest, - GetBuildTriggerRequest, - GetWorkerPoolRequest, - GitHubEventsConfig, - Hash, - InlineSecret, - ListBuildsRequest, - ListBuildsResponse, - ListBuildTriggersRequest, - ListBuildTriggersResponse, - ListWorkerPoolsRequest, - ListWorkerPoolsResponse, - PrivatePoolV1Config, - PubsubConfig, - PullRequestFilter, - PushFilter, - ReceiveTriggerWebhookRequest, - ReceiveTriggerWebhookResponse, - RepoSource, - Results, - RetryBuildRequest, - RunBuildTriggerRequest, - Secret, - SecretManagerSecret, - Secrets, - Source, - SourceProvenance, - StorageSource, - StorageSourceManifest, - TimeSpan, - UpdateBuildTriggerRequest, - UpdateWorkerPoolOperationMetadata, - UpdateWorkerPoolRequest, - Volume, - WebhookConfig, - WorkerPool, -) - -__all__ = ( - 'ArtifactResult', - 'Artifacts', - 'Build', - 'BuildOperationMetadata', - 'BuildOptions', - 'BuildStep', - 'BuildTrigger', - 'BuiltImage', - 'CancelBuildRequest', - 'CreateBuildRequest', - 'CreateBuildTriggerRequest', - 'CreateWorkerPoolOperationMetadata', - 'CreateWorkerPoolRequest', - 'DeleteBuildTriggerRequest', - 'DeleteWorkerPoolOperationMetadata', - 'DeleteWorkerPoolRequest', - 'FileHashes', - 'GetBuildRequest', - 'GetBuildTriggerRequest', - 'GetWorkerPoolRequest', - 'GitHubEventsConfig', - 'Hash', - 'InlineSecret', - 'ListBuildsRequest', - 'ListBuildsResponse', - 'ListBuildTriggersRequest', - 'ListBuildTriggersResponse', - 'ListWorkerPoolsRequest', - 'ListWorkerPoolsResponse', - 'PrivatePoolV1Config', - 'PubsubConfig', - 'PullRequestFilter', - 'PushFilter', - 'ReceiveTriggerWebhookRequest', - 'ReceiveTriggerWebhookResponse', - 'RepoSource', - 'Results', - 'RetryBuildRequest', - 'RunBuildTriggerRequest', - 'Secret', - 'SecretManagerSecret', - 'Secrets', - 'Source', - 'SourceProvenance', - 'StorageSource', - 'StorageSourceManifest', - 'TimeSpan', - 'UpdateBuildTriggerRequest', - 'UpdateWorkerPoolOperationMetadata', - 'UpdateWorkerPoolRequest', - 'Volume', - 'WebhookConfig', - 'WorkerPool', -) diff --git a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/cloudbuild.py b/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/cloudbuild.py deleted file mode 100644 index d5c68665..00000000 --- a/owl-bot-staging/v1/google/devtools/cloudbuild_v1/types/cloudbuild.py +++ /dev/null @@ -1,2693 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.api import httpbody_pb2 # 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.devtools.cloudbuild.v1', - manifest={ - 'RetryBuildRequest', - 'RunBuildTriggerRequest', - 'StorageSource', - 'RepoSource', - 'StorageSourceManifest', - 'Source', - 'BuiltImage', - 'BuildStep', - 'Volume', - 'Results', - 'ArtifactResult', - 'Build', - 'Artifacts', - 'TimeSpan', - 'BuildOperationMetadata', - 'SourceProvenance', - 'FileHashes', - 'Hash', - 'Secrets', - 'InlineSecret', - 'SecretManagerSecret', - 'Secret', - 'CreateBuildRequest', - 'GetBuildRequest', - 'ListBuildsRequest', - 'ListBuildsResponse', - 'CancelBuildRequest', - 'BuildTrigger', - 'GitHubEventsConfig', - 'PubsubConfig', - 'WebhookConfig', - 'PullRequestFilter', - 'PushFilter', - 'CreateBuildTriggerRequest', - 'GetBuildTriggerRequest', - 'ListBuildTriggersRequest', - 'ListBuildTriggersResponse', - 'DeleteBuildTriggerRequest', - 'UpdateBuildTriggerRequest', - 'BuildOptions', - 'ReceiveTriggerWebhookRequest', - 'ReceiveTriggerWebhookResponse', - 'WorkerPool', - 'PrivatePoolV1Config', - 'CreateWorkerPoolRequest', - 'GetWorkerPoolRequest', - 'DeleteWorkerPoolRequest', - 'UpdateWorkerPoolRequest', - 'ListWorkerPoolsRequest', - 'ListWorkerPoolsResponse', - 'CreateWorkerPoolOperationMetadata', - 'UpdateWorkerPoolOperationMetadata', - 'DeleteWorkerPoolOperationMetadata', - }, -) - - -class RetryBuildRequest(proto.Message): - r"""Specifies a build to retry. - Attributes: - name (str): - The name of the ``Build`` to retry. Format: - ``projects/{project}/locations/{location}/builds/{build}`` - project_id (str): - Required. ID of the project. - id (str): - Required. Build ID of the original build. - """ - - name = proto.Field( - proto.STRING, - number=3, - ) - project_id = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - - -class RunBuildTriggerRequest(proto.Message): - r"""Specifies a build trigger to run and the source to use. - Attributes: - name (str): - The name of the ``Trigger`` to run. Format: - ``projects/{project}/locations/{location}/triggers/{trigger}`` - project_id (str): - Required. ID of the project. - trigger_id (str): - Required. ID of the trigger. - source (google.devtools.cloudbuild_v1.types.RepoSource): - Source to build against this trigger. - """ - - name = proto.Field( - proto.STRING, - number=4, - ) - project_id = proto.Field( - proto.STRING, - number=1, - ) - trigger_id = proto.Field( - proto.STRING, - number=2, - ) - source = proto.Field( - proto.MESSAGE, - number=3, - message='RepoSource', - ) - - -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. - Attributes: - 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. - 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 - 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 - commit_sha (str): - Explicit commit SHA to build. - 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. - invert_regex (bool): - Only trigger a build if the revision regex - does NOT match the revision regex. - substitutions (Sequence[google.devtools.cloudbuild_v1.types.RepoSource.SubstitutionsEntry]): - Substitutions to use in a triggered build. - Should only be used with RunBuildTrigger - """ - - project_id = proto.Field( - proto.STRING, - number=1, - ) - repo_name = proto.Field( - proto.STRING, - number=2, - ) - 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', - ) - dir_ = proto.Field( - proto.STRING, - number=7, - ) - invert_regex = proto.Field( - proto.BOOL, - number=8, - ) - substitutions = proto.MapField( - proto.STRING, - proto.STRING, - number=9, - ) - - -class StorageSourceManifest(proto.Message): - r"""Location of the source manifest in Google Cloud Storage. This - feature is in Preview; see description - `here `__. - - Attributes: - bucket (str): - Google Cloud Storage bucket containing the source manifest - (see `Bucket Name - Requirements `__). - object_ (str): - Google Cloud Storage object containing the - source manifest. - This object must be a JSON file. - 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 Source(proto.Message): - r"""Location of the source in a supported storage service. - Attributes: - storage_source (google.devtools.cloudbuild_v1.types.StorageSource): - If provided, get the source from this - location in Google Cloud Storage. - repo_source (google.devtools.cloudbuild_v1.types.RepoSource): - If provided, get the source from this - location in a Cloud Source Repository. - storage_source_manifest (google.devtools.cloudbuild_v1.types.StorageSourceManifest): - If provided, get the source from this manifest in Google - Cloud Storage. This feature is in Preview; see description - `here `__. - """ - - storage_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='StorageSource', - ) - repo_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='RepoSource', - ) - storage_source_manifest = proto.Field( - proto.MESSAGE, - number=8, - oneof='source', - message='StorageSourceManifest', - ) - - -class BuiltImage(proto.Message): - r"""An image built by the pipeline. - Attributes: - name (str): - Name used to push the container image to Google Container - Registry, as presented to ``docker push``. - digest (str): - Docker Registry 2.0 digest. - push_timing (google.devtools.cloudbuild_v1.types.TimeSpan): - Output only. Stores timing information for - pushing the specified image. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - digest = proto.Field( - proto.STRING, - number=3, - ) - push_timing = proto.Field( - proto.MESSAGE, - number=4, - message='TimeSpan', - ) - - -class BuildStep(proto.Message): - r"""A step in the build pipeline. - Attributes: - name (str): - Required. The name of the container image that will run this - particular build step. - - If the image is available in the host's Docker daemon's - cache, it will be run directly. If not, the host will - attempt to pull the image first, using the builder service - account's credentials if necessary. - - The Docker daemon's cache will already have the latest - versions of all of the officially supported build steps - (https://github.com/GoogleCloudPlatform/cloud-builders). The - Docker daemon will also have cached many of the layers for - some popular images, like "ubuntu", "debian", but they will - be refreshed at the time you attempt to use them. - - If you built an image in a previous build step, it will be - stored in the host's Docker daemon's cache and is available - to use as the name for a later build step. - env (Sequence[str]): - A list of environment variable definitions to - be used when running a step. - The elements are of the form "KEY=VALUE" for the - environment variable "KEY" being given the value - "VALUE". - args (Sequence[str]): - A list of arguments that will be presented to the step when - it is started. - - If the image used to run the step's container has an - entrypoint, the ``args`` are used as arguments to that - entrypoint. If the image does not define an entrypoint, the - first element in args is used as the entrypoint, and the - remainder will be used as arguments. - dir_ (str): - Working directory to use when running this step's container. - - If this value is a relative path, it is relative to the - build's working directory. If this value is absolute, it may - be outside the build's working directory, in which case the - contents of the path may not be persisted across build step - executions, unless a ``volume`` for that path is specified. - - If the build specifies a ``RepoSource`` with ``dir`` and a - step with a ``dir``, which specifies an absolute path, the - ``RepoSource`` ``dir`` is ignored for the step's execution. - id (str): - Unique identifier for this build step, used in ``wait_for`` - to reference this build step as a dependency. - wait_for (Sequence[str]): - The ID(s) of the step(s) that this build step depends on. - This build step will not start until all the build steps in - ``wait_for`` have completed successfully. If ``wait_for`` is - empty, this build step will start when all previous build - steps in the ``Build.Steps`` list have completed - successfully. - entrypoint (str): - Entrypoint to be used instead of the build - step image's default entrypoint. If unset, the - image's default entrypoint is used. - secret_env (Sequence[str]): - A list of environment variables which are encrypted using a - Cloud Key Management Service crypto key. These values must - be specified in the build's ``Secret``. - volumes (Sequence[google.devtools.cloudbuild_v1.types.Volume]): - List of volumes to mount into the build step. - Each volume is created as an empty volume prior - to execution of the build step. Upon completion - of the build, volumes and their contents are - discarded. - - Using a named volume in only one step is not - valid as it is indicative of a build request - with an incorrect configuration. - timing (google.devtools.cloudbuild_v1.types.TimeSpan): - Output only. Stores timing information for - executing this build step. - pull_timing (google.devtools.cloudbuild_v1.types.TimeSpan): - Output only. Stores timing information for - pulling this build step's builder image only. - timeout (google.protobuf.duration_pb2.Duration): - Time limit for executing this build step. If - not defined, the step has no time limit and will - be allowed to continue to run until either it - completes or the build itself times out. - status (google.devtools.cloudbuild_v1.types.Build.Status): - Output only. Status of the build step. At - this time, build step status is only updated on - build completion; step status is not updated in - real-time as the build progresses. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - env = proto.RepeatedField( - proto.STRING, - number=2, - ) - args = proto.RepeatedField( - proto.STRING, - number=3, - ) - dir_ = proto.Field( - proto.STRING, - number=4, - ) - id = proto.Field( - proto.STRING, - number=5, - ) - wait_for = proto.RepeatedField( - proto.STRING, - number=6, - ) - entrypoint = proto.Field( - proto.STRING, - number=7, - ) - secret_env = proto.RepeatedField( - proto.STRING, - number=8, - ) - volumes = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='Volume', - ) - timing = proto.Field( - proto.MESSAGE, - number=10, - message='TimeSpan', - ) - pull_timing = proto.Field( - proto.MESSAGE, - number=13, - message='TimeSpan', - ) - timeout = proto.Field( - proto.MESSAGE, - number=11, - message=duration_pb2.Duration, - ) - status = proto.Field( - proto.ENUM, - number=12, - enum='Build.Status', - ) - - -class Volume(proto.Message): - r"""Volume describes a Docker container volume which is mounted - into build steps in order to persist files across build step - execution. - - Attributes: - name (str): - Name of the volume to mount. - Volume names must be unique per build step and - must be valid names for Docker volumes. Each - named volume must be used by at least two build - steps. - path (str): - Path at which to mount the volume. - Paths must be absolute and cannot conflict with - other volume paths on the same build step or - with certain reserved volume paths. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - path = proto.Field( - proto.STRING, - number=2, - ) - - -class Results(proto.Message): - r"""Artifacts created by the build pipeline. - Attributes: - images (Sequence[google.devtools.cloudbuild_v1.types.BuiltImage]): - Container images that were built as a part of - the build. - build_step_images (Sequence[str]): - List of build step digests, in the order - corresponding to build step indices. - artifact_manifest (str): - Path to the artifact manifest. Only populated - when artifacts are uploaded. - num_artifacts (int): - Number of artifacts uploaded. Only populated - when artifacts are uploaded. - build_step_outputs (Sequence[bytes]): - List of build step outputs, produced by builder images, in - the order corresponding to build step indices. - - `Cloud - Builders `__ - can produce this output by writing to - ``$BUILDER_OUTPUT/output``. Only the first 4KB of data is - stored. - artifact_timing (google.devtools.cloudbuild_v1.types.TimeSpan): - Time to push all non-container artifacts. - """ - - images = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='BuiltImage', - ) - build_step_images = proto.RepeatedField( - proto.STRING, - number=3, - ) - artifact_manifest = proto.Field( - proto.STRING, - number=4, - ) - num_artifacts = proto.Field( - proto.INT64, - number=5, - ) - build_step_outputs = proto.RepeatedField( - proto.BYTES, - number=6, - ) - artifact_timing = proto.Field( - proto.MESSAGE, - number=7, - message='TimeSpan', - ) - - -class ArtifactResult(proto.Message): - r"""An artifact that was uploaded during a build. This - is a single record in the artifact manifest JSON file. - - Attributes: - location (str): - The path of an artifact in a Google Cloud Storage bucket, - with the generation number. For example, - ``gs://mybucket/path/to/output.jar#generation``. - file_hash (Sequence[google.devtools.cloudbuild_v1.types.FileHashes]): - The file hash of the artifact. - """ - - location = proto.Field( - proto.STRING, - number=1, - ) - file_hash = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='FileHashes', - ) - - -class Build(proto.Message): - r"""A build resource in the Cloud Build API. - - At a high level, a ``Build`` describes where to find source code, - how to build it (for example, the builder image to run on the - source), and where to store the built artifacts. - - Fields can include the following variables, which will be expanded - when the build is created: - - - $PROJECT_ID: the project ID of the build. - - $PROJECT_NUMBER: the project number of the build. - - $BUILD_ID: the autogenerated ID of the build. - - $REPO_NAME: the source repository name specified by RepoSource. - - $BRANCH_NAME: the branch name specified by RepoSource. - - $TAG_NAME: the tag name specified by RepoSource. - - $REVISION_ID or $COMMIT_SHA: the commit SHA specified by - RepoSource or resolved from the specified branch or tag. - - $SHORT_SHA: first 7 characters of $REVISION_ID or $COMMIT_SHA. - - Attributes: - name (str): - Output only. The 'Build' name with format: - ``projects/{project}/locations/{location}/builds/{build}``, - where {build} is a unique identifier generated by the - service. - id (str): - Output only. Unique identifier of the build. - project_id (str): - Output only. ID of the project. - status (google.devtools.cloudbuild_v1.types.Build.Status): - Output only. Status of the build. - status_detail (str): - Output only. Customer-readable message about - the current status. - source (google.devtools.cloudbuild_v1.types.Source): - The location of the source files to build. - steps (Sequence[google.devtools.cloudbuild_v1.types.BuildStep]): - Required. The operations to be performed on - the workspace. - results (google.devtools.cloudbuild_v1.types.Results): - Output only. Results of the build. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time at which the request to - create the build was received. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time at which execution of the - build was started. - finish_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time at which execution of the build was - finished. - - The difference between finish_time and start_time is the - duration of the build's execution. - timeout (google.protobuf.duration_pb2.Duration): - Amount of time that this build should be allowed to run, to - second granularity. If this amount of time elapses, work on - the build will cease and the build status will be - ``TIMEOUT``. - - ``timeout`` starts ticking from ``startTime``. - - Default time is ten minutes. - images (Sequence[str]): - A list of images to be pushed upon the successful completion - of all build steps. - - The images are pushed using the builder service account's - credentials. - - The digests of the pushed images will be stored in the - ``Build`` resource's results field. - - If any of the images fail to be pushed, the build status is - marked ``FAILURE``. - queue_ttl (google.protobuf.duration_pb2.Duration): - TTL in queue for this build. If provided and the build is - enqueued longer than this value, the build will expire and - the build status will be ``EXPIRED``. - - The TTL starts ticking from create_time. - artifacts (google.devtools.cloudbuild_v1.types.Artifacts): - Artifacts produced by the build that should - be uploaded upon successful completion of all - build steps. - logs_bucket (str): - Google Cloud Storage bucket where logs should be written - (see `Bucket Name - Requirements `__). - Logs file names will be of the format - ``${logs_bucket}/log-${build_id}.txt``. - source_provenance (google.devtools.cloudbuild_v1.types.SourceProvenance): - Output only. A permanent fixed identifier for - source. - build_trigger_id (str): - Output only. The ID of the ``BuildTrigger`` that triggered - this build, if it was triggered automatically. - options (google.devtools.cloudbuild_v1.types.BuildOptions): - Special options for this build. - log_url (str): - Output only. URL to logs for this build in - Google Cloud Console. - substitutions (Sequence[google.devtools.cloudbuild_v1.types.Build.SubstitutionsEntry]): - Substitutions data for ``Build`` resource. - tags (Sequence[str]): - Tags for annotation of a ``Build``. These are not docker - tags. - secrets (Sequence[google.devtools.cloudbuild_v1.types.Secret]): - Secrets to decrypt using Cloud Key Management Service. Note: - Secret Manager is the recommended technique for managing - sensitive data with Cloud Build. Use ``available_secrets`` - to configure builds to access secrets from Secret Manager. - For instructions, see: - https://cloud.google.com/cloud-build/docs/securing-builds/use-secrets - timing (Sequence[google.devtools.cloudbuild_v1.types.Build.TimingEntry]): - Output only. Stores timing information for phases of the - build. Valid keys are: - - - BUILD: time to execute all build steps - - PUSH: time to push all specified images. - - FETCHSOURCE: time to fetch source. - - If the build does not specify source or images, these keys - will not be included. - service_account (str): - IAM service account whose credentials will be used at build - runtime. Must be of the format - ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. ACCOUNT - can be email address or uniqueId of the service account. - available_secrets (google.devtools.cloudbuild_v1.types.Secrets): - Secrets and secret environment variables. - warnings (Sequence[google.devtools.cloudbuild_v1.types.Build.Warning]): - Output only. Non-fatal problems encountered - during the execution of the build. - failure_info (google.devtools.cloudbuild_v1.types.Build.FailureInfo): - Output only. Contains information about the - build when status=FAILURE. - """ - class Status(proto.Enum): - r"""Possible status of a build or build step.""" - STATUS_UNKNOWN = 0 - QUEUED = 1 - WORKING = 2 - SUCCESS = 3 - FAILURE = 4 - INTERNAL_ERROR = 5 - TIMEOUT = 6 - CANCELLED = 7 - EXPIRED = 9 - - class Warning(proto.Message): - r"""A non-fatal problem encountered during the execution of the - build. - - Attributes: - text (str): - Explanation of the warning generated. - priority (google.devtools.cloudbuild_v1.types.Build.Warning.Priority): - The priority for this warning. - """ - class Priority(proto.Enum): - r"""The relative importance of this warning.""" - PRIORITY_UNSPECIFIED = 0 - INFO = 1 - WARNING = 2 - ALERT = 3 - - text = proto.Field( - proto.STRING, - number=1, - ) - priority = proto.Field( - proto.ENUM, - number=2, - enum='Build.Warning.Priority', - ) - - class FailureInfo(proto.Message): - r"""A fatal problem encountered during the execution of the - build. - - Attributes: - type_ (google.devtools.cloudbuild_v1.types.Build.FailureInfo.FailureType): - The name of the failure. - detail (str): - Explains the failure issue in more detail - using hard-coded text. - """ - class FailureType(proto.Enum): - r"""The name of a fatal problem encountered during the execution - of the build. - """ - FAILURE_TYPE_UNSPECIFIED = 0 - PUSH_FAILED = 1 - PUSH_IMAGE_NOT_FOUND = 2 - PUSH_NOT_AUTHORIZED = 3 - LOGGING_FAILURE = 4 - USER_BUILD_STEP = 5 - FETCH_SOURCE_FAILED = 6 - - type_ = proto.Field( - proto.ENUM, - number=1, - enum='Build.FailureInfo.FailureType', - ) - detail = proto.Field( - proto.STRING, - number=2, - ) - - name = proto.Field( - proto.STRING, - number=45, - ) - id = proto.Field( - proto.STRING, - number=1, - ) - project_id = proto.Field( - proto.STRING, - number=16, - ) - status = proto.Field( - proto.ENUM, - number=2, - enum=Status, - ) - status_detail = proto.Field( - proto.STRING, - number=24, - ) - source = proto.Field( - proto.MESSAGE, - number=3, - message='Source', - ) - steps = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='BuildStep', - ) - results = proto.Field( - proto.MESSAGE, - number=10, - message='Results', - ) - create_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - start_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - finish_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - timeout = proto.Field( - proto.MESSAGE, - number=12, - message=duration_pb2.Duration, - ) - images = proto.RepeatedField( - proto.STRING, - number=13, - ) - queue_ttl = proto.Field( - proto.MESSAGE, - number=40, - message=duration_pb2.Duration, - ) - artifacts = proto.Field( - proto.MESSAGE, - number=37, - message='Artifacts', - ) - logs_bucket = proto.Field( - proto.STRING, - number=19, - ) - source_provenance = proto.Field( - proto.MESSAGE, - number=21, - message='SourceProvenance', - ) - build_trigger_id = proto.Field( - proto.STRING, - number=22, - ) - options = proto.Field( - proto.MESSAGE, - number=23, - message='BuildOptions', - ) - log_url = proto.Field( - proto.STRING, - number=25, - ) - substitutions = proto.MapField( - proto.STRING, - proto.STRING, - number=29, - ) - tags = proto.RepeatedField( - proto.STRING, - number=31, - ) - secrets = proto.RepeatedField( - proto.MESSAGE, - number=32, - message='Secret', - ) - timing = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=33, - message='TimeSpan', - ) - service_account = proto.Field( - proto.STRING, - number=42, - ) - available_secrets = proto.Field( - proto.MESSAGE, - number=47, - message='Secrets', - ) - warnings = proto.RepeatedField( - proto.MESSAGE, - number=49, - message=Warning, - ) - failure_info = proto.Field( - proto.MESSAGE, - number=51, - message=FailureInfo, - ) - - -class Artifacts(proto.Message): - r"""Artifacts produced by a build that should be uploaded upon - successful completion of all build steps. - - Attributes: - images (Sequence[str]): - A list of images to be pushed upon the - successful completion of all build steps. - - The images will be pushed using the builder - service account's credentials. - The digests of the pushed images will be stored - in the Build resource's results field. - - If any of the images fail to be pushed, the - build is marked FAILURE. - objects (google.devtools.cloudbuild_v1.types.Artifacts.ArtifactObjects): - A list of objects to be uploaded to Cloud - Storage upon successful completion of all build - steps. - Files in the workspace matching specified paths - globs will be uploaded to the specified Cloud - Storage location using the builder service - account's credentials. - - The location and generation of the uploaded - objects will be stored in the Build resource's - results field. - - If any objects fail to be pushed, the build is - marked FAILURE. - """ - - class ArtifactObjects(proto.Message): - r"""Files in the workspace to upload to Cloud Storage upon - successful completion of all build steps. - - Attributes: - location (str): - Cloud Storage bucket and optional object path, in the form - "gs://bucket/path/to/somewhere/". (see `Bucket Name - Requirements `__). - - Files in the workspace matching any path pattern will be - uploaded to Cloud Storage with this location as a prefix. - paths (Sequence[str]): - Path globs used to match files in the build's - workspace. - timing (google.devtools.cloudbuild_v1.types.TimeSpan): - Output only. Stores timing information for - pushing all artifact objects. - """ - - location = proto.Field( - proto.STRING, - number=1, - ) - paths = proto.RepeatedField( - proto.STRING, - number=2, - ) - timing = proto.Field( - proto.MESSAGE, - number=3, - message='TimeSpan', - ) - - images = proto.RepeatedField( - proto.STRING, - number=1, - ) - objects = proto.Field( - proto.MESSAGE, - number=2, - message=ArtifactObjects, - ) - - -class TimeSpan(proto.Message): - r"""Start and end times for a build execution phase. - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start of time span. - end_time (google.protobuf.timestamp_pb2.Timestamp): - End of time span. - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class BuildOperationMetadata(proto.Message): - r"""Metadata for build operations. - Attributes: - build (google.devtools.cloudbuild_v1.types.Build): - The build that the operation is tracking. - """ - - build = proto.Field( - proto.MESSAGE, - number=1, - message='Build', - ) - - -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.devtools.cloudbuild_v1.types.StorageSource): - A copy of the build's ``source.storage_source``, if exists, - with any generations resolved. - resolved_repo_source (google.devtools.cloudbuild_v1.types.RepoSource): - A copy of the build's ``source.repo_source``, if exists, - with any revisions resolved. - resolved_storage_source_manifest (google.devtools.cloudbuild_v1.types.StorageSourceManifest): - A copy of the build's ``source.storage_source_manifest``, if - exists, with any revisions resolved. This feature is in - Preview. - file_hashes (Sequence[google.devtools.cloudbuild_v1.types.SourceProvenance.FileHashesEntry]): - Output only. Hash(es) of the build source, which can be used - to verify that the original source integrity was maintained - in the build. Note that ``FileHashes`` will only be - populated if ``BuildOptions`` has requested a - ``SourceProvenanceHash``. - - The keys to this map are file paths used as build source and - the values contain the hash values for those files. - - If the build source came in a single package such as a - gzipped tarfile (``.tar.gz``), the ``FileHash`` will be for - the single path to that file. - """ - - resolved_storage_source = proto.Field( - proto.MESSAGE, - number=3, - message='StorageSource', - ) - resolved_repo_source = proto.Field( - proto.MESSAGE, - number=6, - message='RepoSource', - ) - resolved_storage_source_manifest = proto.Field( - proto.MESSAGE, - number=9, - message='StorageSourceManifest', - ) - file_hashes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message='FileHashes', - ) - - -class FileHashes(proto.Message): - r"""Container message for hashes of byte content of files, used - in SourceProvenance messages to verify integrity of source input - to the build. - - Attributes: - file_hash (Sequence[google.devtools.cloudbuild_v1.types.Hash]): - Collection of file hashes. - """ - - file_hash = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Hash', - ) - - -class Hash(proto.Message): - r"""Container message for hash values. - Attributes: - type_ (google.devtools.cloudbuild_v1.types.Hash.HashType): - The type of hash that was performed. - value (bytes): - The hash value. - """ - class HashType(proto.Enum): - r"""Specifies the hash algorithm, if any.""" - NONE = 0 - SHA256 = 1 - MD5 = 2 - - type_ = proto.Field( - proto.ENUM, - number=1, - enum=HashType, - ) - value = proto.Field( - proto.BYTES, - number=2, - ) - - -class Secrets(proto.Message): - r"""Secrets and secret environment variables. - Attributes: - secret_manager (Sequence[google.devtools.cloudbuild_v1.types.SecretManagerSecret]): - Secrets in Secret Manager and associated - secret environment variable. - inline (Sequence[google.devtools.cloudbuild_v1.types.InlineSecret]): - Secrets encrypted with KMS key and the - associated secret environment variable. - """ - - secret_manager = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SecretManagerSecret', - ) - inline = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='InlineSecret', - ) - - -class InlineSecret(proto.Message): - r"""Pairs a set of secret environment variables mapped to - encrypted values with the Cloud KMS key to use to decrypt the - value. - - Attributes: - kms_key_name (str): - Resource name of Cloud KMS crypto key to decrypt the - encrypted value. In format: - projects/\ */locations/*/keyRings/*/cryptoKeys/* - env_map (Sequence[google.devtools.cloudbuild_v1.types.InlineSecret.EnvMapEntry]): - Map of environment variable name to its - encrypted value. - Secret environment variables must be unique - across all of a build's secrets, and must be - used by at least one build step. Values can be - at most 64 KB in size. There can be at most 100 - secret values across all of a build's secrets. - """ - - kms_key_name = proto.Field( - proto.STRING, - number=1, - ) - env_map = proto.MapField( - proto.STRING, - proto.BYTES, - number=2, - ) - - -class SecretManagerSecret(proto.Message): - r"""Pairs a secret environment variable with a SecretVersion in - Secret Manager. - - Attributes: - version_name (str): - Resource name of the SecretVersion. In format: - projects/\ */secrets/*/versions/\* - env (str): - Environment variable name to associate with - the secret. Secret environment variables must be - unique across all of a build's secrets, and must - be used by at least one build step. - """ - - version_name = proto.Field( - proto.STRING, - number=1, - ) - env = proto.Field( - proto.STRING, - number=2, - ) - - -class Secret(proto.Message): - r"""Pairs a set of secret environment variables containing encrypted - values with the Cloud KMS key to use to decrypt the value. Note: Use - ``kmsKeyName`` with ``available_secrets`` instead of using - ``kmsKeyName`` with ``secret``. For instructions see: - https://cloud.google.com/cloud-build/docs/securing-builds/use-encrypted-credentials. - - Attributes: - kms_key_name (str): - Cloud KMS key name to use to decrypt these - envs. - secret_env (Sequence[google.devtools.cloudbuild_v1.types.Secret.SecretEnvEntry]): - Map of environment variable name to its - encrypted value. - Secret environment variables must be unique - across all of a build's secrets, and must be - used by at least one build step. Values can be - at most 64 KB in size. There can be at most 100 - secret values across all of a build's secrets. - """ - - kms_key_name = proto.Field( - proto.STRING, - number=1, - ) - secret_env = proto.MapField( - proto.STRING, - proto.BYTES, - number=3, - ) - - -class CreateBuildRequest(proto.Message): - r"""Request to create a new build. - Attributes: - parent (str): - The parent resource where this build will be created. - Format: ``projects/{project}/locations/{location}`` - project_id (str): - Required. ID of the project. - build (google.devtools.cloudbuild_v1.types.Build): - Required. Build resource to create. - """ - - parent = proto.Field( - proto.STRING, - number=4, - ) - project_id = proto.Field( - proto.STRING, - number=1, - ) - build = proto.Field( - proto.MESSAGE, - number=2, - message='Build', - ) - - -class GetBuildRequest(proto.Message): - r"""Request to get a build. - Attributes: - name (str): - The name of the ``Build`` to retrieve. Format: - ``projects/{project}/locations/{location}/builds/{build}`` - project_id (str): - Required. ID of the project. - id (str): - Required. ID of the build. - """ - - name = proto.Field( - proto.STRING, - number=4, - ) - project_id = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - - -class ListBuildsRequest(proto.Message): - r"""Request to list builds. - Attributes: - parent (str): - The parent of the collection of ``Builds``. Format: - ``projects/{project}/locations/location`` - project_id (str): - Required. ID of the project. - page_size (int): - Number of results to return in the list. - page_token (str): - The page token for the next page of Builds. - - If unspecified, the first page of results is returned. - - If the token is rejected for any reason, INVALID_ARGUMENT - will be thrown. In this case, the token should be discarded, - and pagination should be restarted from the first page of - results. - - See https://google.aip.dev/158 for more. - filter (str): - The raw filter text to constrain the results. - """ - - parent = proto.Field( - proto.STRING, - number=9, - ) - project_id = 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=8, - ) - - -class ListBuildsResponse(proto.Message): - r"""Response including listed builds. - Attributes: - builds (Sequence[google.devtools.cloudbuild_v1.types.Build]): - Builds will be sorted by ``create_time``, descending. - next_page_token (str): - Token to receive the next page of results. - This will be absent if the end of the response - list has been reached. - """ - - @property - def raw_page(self): - return self - - builds = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Build', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CancelBuildRequest(proto.Message): - r"""Request to cancel an ongoing build. - Attributes: - name (str): - The name of the ``Build`` to cancel. Format: - ``projects/{project}/locations/{location}/builds/{build}`` - project_id (str): - Required. ID of the project. - id (str): - Required. ID of the build. - """ - - name = proto.Field( - proto.STRING, - number=4, - ) - project_id = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - - -class BuildTrigger(proto.Message): - r"""Configuration for an automated build in response to source - repository changes. - - Attributes: - resource_name (str): - The ``Trigger`` name with format: - ``projects/{project}/locations/{location}/triggers/{trigger}``, - where {trigger} is a unique identifier generated by the - service. - id (str): - Output only. Unique identifier of the - trigger. - description (str): - Human-readable description of this trigger. - name (str): - User-assigned name of the trigger. Must be - unique within the project. Trigger names must - meet the following requirements: - + They must contain only alphanumeric characters - and dashes. + They can be 1-64 characters long. - + They must begin and end with an alphanumeric - character. - tags (Sequence[str]): - Tags for annotation of a ``BuildTrigger`` - trigger_template (google.devtools.cloudbuild_v1.types.RepoSource): - Template describing the types of source changes to trigger a - build. - - Branch and tag names in trigger templates are interpreted as - regular expressions. Any branch or tag change that matches - that regular expression will trigger a build. - - Mutually exclusive with ``github``. - github (google.devtools.cloudbuild_v1.types.GitHubEventsConfig): - GitHubEventsConfig describes the configuration of a trigger - that creates a build whenever a GitHub event is received. - - Mutually exclusive with ``trigger_template``. - pubsub_config (google.devtools.cloudbuild_v1.types.PubsubConfig): - PubsubConfig describes the configuration of a - trigger that creates a build whenever a Pub/Sub - message is published. - webhook_config (google.devtools.cloudbuild_v1.types.WebhookConfig): - WebhookConfig describes the configuration of - a trigger that creates a build whenever a - webhook is sent to a trigger's webhook URL. - autodetect (bool): - Autodetect build configuration. The - following precedence is used (case insensitive): - 1. cloudbuild.yaml - 2. cloudbuild.yml - 3. cloudbuild.json - 4. Dockerfile - - Currently only available for GitHub App - Triggers. - build (google.devtools.cloudbuild_v1.types.Build): - Contents of the build template. - filename (str): - Path, from the source root, to the build - configuration file (i.e. cloudbuild.yaml). - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when the trigger was - created. - disabled (bool): - If true, the trigger will never automatically - execute a build. - substitutions (Sequence[google.devtools.cloudbuild_v1.types.BuildTrigger.SubstitutionsEntry]): - Substitutions for Build resource. The keys must match the - following regular expression: ``^_[A-Z0-9_]+$``. - ignored_files (Sequence[str]): - ignored_files and included_files are file glob matches using - https://golang.org/pkg/path/filepath/#Match extended with - support for "**". - - If ignored_files and changed files are both empty, then they - are not used to determine whether or not to trigger a build. - - If ignored_files is not empty, then we ignore any files that - match any of the ignored_file globs. If the change has no - files that are outside of the ignored_files globs, then we - do not trigger a build. - included_files (Sequence[str]): - If any of the files altered in the commit pass the - ignored_files filter and included_files is empty, then as - far as this filter is concerned, we should trigger the - build. - - If any of the files altered in the commit pass the - ignored_files filter and included_files is not empty, then - we make sure that at least one of those files matches a - included_files glob. If not, then we do not trigger a build. - filter (str): - Optional. A Common Expression Language - string. - """ - - resource_name = proto.Field( - proto.STRING, - number=34, - ) - id = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=10, - ) - name = proto.Field( - proto.STRING, - number=21, - ) - tags = proto.RepeatedField( - proto.STRING, - number=19, - ) - trigger_template = proto.Field( - proto.MESSAGE, - number=7, - message='RepoSource', - ) - github = proto.Field( - proto.MESSAGE, - number=13, - message='GitHubEventsConfig', - ) - pubsub_config = proto.Field( - proto.MESSAGE, - number=29, - message='PubsubConfig', - ) - webhook_config = proto.Field( - proto.MESSAGE, - number=31, - message='WebhookConfig', - ) - autodetect = proto.Field( - proto.BOOL, - number=18, - oneof='build_template', - ) - build = proto.Field( - proto.MESSAGE, - number=4, - oneof='build_template', - message='Build', - ) - filename = proto.Field( - proto.STRING, - number=8, - oneof='build_template', - ) - create_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - disabled = proto.Field( - proto.BOOL, - number=9, - ) - substitutions = proto.MapField( - proto.STRING, - proto.STRING, - number=11, - ) - ignored_files = proto.RepeatedField( - proto.STRING, - number=15, - ) - included_files = proto.RepeatedField( - proto.STRING, - number=16, - ) - filter = proto.Field( - proto.STRING, - number=30, - ) - - -class GitHubEventsConfig(proto.Message): - r"""GitHubEventsConfig describes the configuration of a trigger - that creates a build whenever a GitHub event is received. - This message is experimental. - - Attributes: - installation_id (int): - The installationID that emits the GitHub - event. - owner (str): - Owner of the repository. For example: The - owner for - https://github.com/googlecloudplatform/cloud- - builders is "googlecloudplatform". - name (str): - Name of the repository. For example: The name - for - https://github.com/googlecloudplatform/cloud- - builders is "cloud-builders". - pull_request (google.devtools.cloudbuild_v1.types.PullRequestFilter): - filter to match changes in pull requests. - push (google.devtools.cloudbuild_v1.types.PushFilter): - filter to match changes in refs like - branches, tags. - """ - - installation_id = proto.Field( - proto.INT64, - number=1, - ) - owner = proto.Field( - proto.STRING, - number=6, - ) - name = proto.Field( - proto.STRING, - number=7, - ) - pull_request = proto.Field( - proto.MESSAGE, - number=4, - oneof='event', - message='PullRequestFilter', - ) - push = proto.Field( - proto.MESSAGE, - number=5, - oneof='event', - message='PushFilter', - ) - - -class PubsubConfig(proto.Message): - r"""PubsubConfig describes the configuration of a trigger that - creates a build whenever a Pub/Sub message is published. - - Attributes: - subscription (str): - Output only. Name of the subscription. Format is - ``projects/{project}/subscriptions/{subscription}``. - topic (str): - The name of the topic from which this subscription is - receiving messages. Format is - ``projects/{project}/topics/{topic}``. - service_account_email (str): - Service account that will make the push - request. - state (google.devtools.cloudbuild_v1.types.PubsubConfig.State): - Potential issues with the underlying Pub/Sub - subscription configuration. Only populated on - get requests. - """ - class State(proto.Enum): - r"""Enumerates potential issues with the underlying Pub/Sub - subscription configuration. - """ - STATE_UNSPECIFIED = 0 - OK = 1 - SUBSCRIPTION_DELETED = 2 - TOPIC_DELETED = 3 - SUBSCRIPTION_MISCONFIGURED = 4 - - subscription = proto.Field( - proto.STRING, - number=1, - ) - topic = proto.Field( - proto.STRING, - number=2, - ) - service_account_email = proto.Field( - proto.STRING, - number=3, - ) - state = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - - -class WebhookConfig(proto.Message): - r"""WebhookConfig describes the configuration of a trigger that - creates a build whenever a webhook is sent to a trigger's - webhook URL. - - Attributes: - secret (str): - Required. Resource name for the secret - required as a URL parameter. - state (google.devtools.cloudbuild_v1.types.WebhookConfig.State): - Potential issues with the underlying Pub/Sub - subscription configuration. Only populated on - get requests. - """ - class State(proto.Enum): - r"""Enumerates potential issues with the Secret Manager secret - provided by the user. - """ - STATE_UNSPECIFIED = 0 - OK = 1 - SECRET_DELETED = 2 - - secret = proto.Field( - proto.STRING, - number=3, - oneof='auth_method', - ) - state = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - - -class PullRequestFilter(proto.Message): - r"""PullRequestFilter contains filter properties for matching - GitHub Pull Requests. - - Attributes: - branch (str): - Regex of branches to match. - The syntax of the regular expressions accepted - is the syntax accepted by RE2 and described at - https://github.com/google/re2/wiki/Syntax - comment_control (google.devtools.cloudbuild_v1.types.PullRequestFilter.CommentControl): - Configure builds to run whether a repository owner or - collaborator need to comment ``/gcbrun``. - invert_regex (bool): - If true, branches that do NOT match the git_ref will trigger - a build. - """ - class CommentControl(proto.Enum): - r"""Controls behavior of Pull Request comments.""" - COMMENTS_DISABLED = 0 - COMMENTS_ENABLED = 1 - COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY = 2 - - branch = proto.Field( - proto.STRING, - number=2, - oneof='git_ref', - ) - comment_control = proto.Field( - proto.ENUM, - number=5, - enum=CommentControl, - ) - invert_regex = proto.Field( - proto.BOOL, - number=6, - ) - - -class PushFilter(proto.Message): - r"""Push contains filter properties for matching GitHub git - pushes. - - Attributes: - branch (str): - Regexes 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 - tag (str): - Regexes 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 - invert_regex (bool): - When true, only trigger a build if the revision regex does - NOT match the git_ref regex. - """ - - branch = proto.Field( - proto.STRING, - number=2, - oneof='git_ref', - ) - tag = proto.Field( - proto.STRING, - number=3, - oneof='git_ref', - ) - invert_regex = proto.Field( - proto.BOOL, - number=4, - ) - - -class CreateBuildTriggerRequest(proto.Message): - r"""Request to create a new ``BuildTrigger``. - Attributes: - parent (str): - The parent resource where this trigger will be created. - Format: ``projects/{project}/locations/{location}`` - project_id (str): - Required. ID of the project for which to - configure automatic builds. - trigger (google.devtools.cloudbuild_v1.types.BuildTrigger): - Required. ``BuildTrigger`` to create. - """ - - parent = proto.Field( - proto.STRING, - number=3, - ) - project_id = proto.Field( - proto.STRING, - number=1, - ) - trigger = proto.Field( - proto.MESSAGE, - number=2, - message='BuildTrigger', - ) - - -class GetBuildTriggerRequest(proto.Message): - r"""Returns the ``BuildTrigger`` with the specified ID. - Attributes: - name (str): - The name of the ``Trigger`` to retrieve. Format: - ``projects/{project}/locations/{location}/triggers/{trigger}`` - project_id (str): - Required. ID of the project that owns the - trigger. - trigger_id (str): - Required. Identifier (``id`` or ``name``) of the - ``BuildTrigger`` to get. - """ - - name = proto.Field( - proto.STRING, - number=3, - ) - project_id = proto.Field( - proto.STRING, - number=1, - ) - trigger_id = proto.Field( - proto.STRING, - number=2, - ) - - -class ListBuildTriggersRequest(proto.Message): - r"""Request to list existing ``BuildTriggers``. - Attributes: - parent (str): - The parent of the collection of ``Triggers``. Format: - ``projects/{project}/locations/{location}`` - project_id (str): - Required. ID of the project for which to list - BuildTriggers. - page_size (int): - Number of results to return in the list. - page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - parent = proto.Field( - proto.STRING, - number=4, - ) - project_id = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListBuildTriggersResponse(proto.Message): - r"""Response containing existing ``BuildTriggers``. - Attributes: - triggers (Sequence[google.devtools.cloudbuild_v1.types.BuildTrigger]): - ``BuildTriggers`` for the project, sorted by ``create_time`` - descending. - next_page_token (str): - Token to receive the next page of results. - """ - - @property - def raw_page(self): - return self - - triggers = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='BuildTrigger', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteBuildTriggerRequest(proto.Message): - r"""Request to delete a ``BuildTrigger``. - Attributes: - name (str): - The name of the ``Trigger`` to delete. Format: - ``projects/{project}/locations/{location}/triggers/{trigger}`` - project_id (str): - Required. ID of the project that owns the - trigger. - trigger_id (str): - Required. ID of the ``BuildTrigger`` to delete. - """ - - name = proto.Field( - proto.STRING, - number=3, - ) - project_id = proto.Field( - proto.STRING, - number=1, - ) - trigger_id = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateBuildTriggerRequest(proto.Message): - r"""Request to update an existing ``BuildTrigger``. - Attributes: - project_id (str): - Required. ID of the project that owns the - trigger. - trigger_id (str): - Required. ID of the ``BuildTrigger`` to update. - trigger (google.devtools.cloudbuild_v1.types.BuildTrigger): - Required. ``BuildTrigger`` to update. - """ - - project_id = proto.Field( - proto.STRING, - number=1, - ) - trigger_id = proto.Field( - proto.STRING, - number=2, - ) - trigger = proto.Field( - proto.MESSAGE, - number=3, - message='BuildTrigger', - ) - - -class BuildOptions(proto.Message): - r"""Optional arguments to enable specific features of builds. - Attributes: - source_provenance_hash (Sequence[google.devtools.cloudbuild_v1.types.Hash.HashType]): - Requested hash for SourceProvenance. - requested_verify_option (google.devtools.cloudbuild_v1.types.BuildOptions.VerifyOption): - Requested verifiability options. - machine_type (google.devtools.cloudbuild_v1.types.BuildOptions.MachineType): - Compute Engine machine type on which to run - the build. - disk_size_gb (int): - Requested disk size for the VM that runs the build. Note - that this is *NOT* "disk free"; some of the space will be - used by the operating system and build utilities. Also note - that this is the minimum disk size that will be allocated - for the build -- the build may run with a larger disk than - requested. At present, the maximum disk size is 1000GB; - builds that request more than the maximum are rejected with - an error. - substitution_option (google.devtools.cloudbuild_v1.types.BuildOptions.SubstitutionOption): - Option to specify behavior when there is an error in the - substitution checks. - - NOTE: this is always set to ALLOW_LOOSE for triggered builds - and cannot be overridden in the build configuration file. - dynamic_substitutions (bool): - Option to specify whether or not to apply - bash style string operations to the - substitutions. - NOTE: this is always enabled for triggered - builds and cannot be overridden in the build - configuration file. - log_streaming_option (google.devtools.cloudbuild_v1.types.BuildOptions.LogStreamingOption): - Option to define build log streaming behavior - to Google Cloud Storage. - worker_pool (str): - This field deprecated; please use ``pool.name`` instead. - pool (google.devtools.cloudbuild_v1.types.BuildOptions.PoolOption): - Optional. Specification for execution on a ``WorkerPool``. - - See `running builds in a private - pool `__ - for more information. - logging (google.devtools.cloudbuild_v1.types.BuildOptions.LoggingMode): - Option to specify the logging mode, which - determines if and where build logs are stored. - env (Sequence[str]): - A list of global environment variable - definitions that will exist for all build steps - in this build. If a variable is defined in both - globally and in a build step, the variable will - use the build step value. - The elements are of the form "KEY=VALUE" for the - environment variable "KEY" being given the value - "VALUE". - secret_env (Sequence[str]): - A list of global environment variables, which are encrypted - using a Cloud Key Management Service crypto key. These - values must be specified in the build's ``Secret``. These - variables will be available to all build steps in this - build. - volumes (Sequence[google.devtools.cloudbuild_v1.types.Volume]): - Global list of volumes to mount for ALL build - steps - Each volume is created as an empty volume prior - to starting the build process. Upon completion - of the build, volumes and their contents are - discarded. Global volume names and paths cannot - conflict with the volumes defined a build step. - - Using a global volume in a build with only one - step is not valid as it is indicative of a build - request with an incorrect configuration. - """ - class VerifyOption(proto.Enum): - r"""Specifies the manner in which the build should be verified, - if at all. - """ - NOT_VERIFIED = 0 - VERIFIED = 1 - - class MachineType(proto.Enum): - r"""Supported Compute Engine machine types. For more information, see - `Machine - types `__. - """ - UNSPECIFIED = 0 - N1_HIGHCPU_8 = 1 - N1_HIGHCPU_32 = 2 - E2_HIGHCPU_8 = 5 - E2_HIGHCPU_32 = 6 - - class SubstitutionOption(proto.Enum): - r"""Specifies the behavior when there is an error in the - substitution checks. - """ - MUST_MATCH = 0 - ALLOW_LOOSE = 1 - - class LogStreamingOption(proto.Enum): - r"""Specifies the behavior when writing build logs to Google - Cloud Storage. - """ - STREAM_DEFAULT = 0 - STREAM_ON = 1 - STREAM_OFF = 2 - - class LoggingMode(proto.Enum): - r"""Specifies the logging mode.""" - LOGGING_UNSPECIFIED = 0 - LEGACY = 1 - GCS_ONLY = 2 - STACKDRIVER_ONLY = 3 - CLOUD_LOGGING_ONLY = 5 - NONE = 4 - - class PoolOption(proto.Message): - r"""Details about how a build should be executed on a ``WorkerPool``. - - See `running builds in a private - pool `__ - for more information. - - Attributes: - name (str): - The ``WorkerPool`` resource to execute the build on. You - must have ``cloudbuild.workerpools.use`` on the project - hosting the WorkerPool. - - Format - projects/{project}/locations/{location}/workerPools/{workerPoolId} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - source_provenance_hash = proto.RepeatedField( - proto.ENUM, - number=1, - enum='Hash.HashType', - ) - requested_verify_option = proto.Field( - proto.ENUM, - number=2, - enum=VerifyOption, - ) - machine_type = proto.Field( - proto.ENUM, - number=3, - enum=MachineType, - ) - disk_size_gb = proto.Field( - proto.INT64, - number=6, - ) - substitution_option = proto.Field( - proto.ENUM, - number=4, - enum=SubstitutionOption, - ) - dynamic_substitutions = proto.Field( - proto.BOOL, - number=17, - ) - log_streaming_option = proto.Field( - proto.ENUM, - number=5, - enum=LogStreamingOption, - ) - worker_pool = proto.Field( - proto.STRING, - number=7, - ) - pool = proto.Field( - proto.MESSAGE, - number=19, - message=PoolOption, - ) - logging = proto.Field( - proto.ENUM, - number=11, - enum=LoggingMode, - ) - env = proto.RepeatedField( - proto.STRING, - number=12, - ) - secret_env = proto.RepeatedField( - proto.STRING, - number=13, - ) - volumes = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='Volume', - ) - - -class ReceiveTriggerWebhookRequest(proto.Message): - r"""ReceiveTriggerWebhookRequest [Experimental] is the request object - accepted by the ReceiveTriggerWebhook method. - - Attributes: - name (str): - The name of the ``ReceiveTriggerWebhook`` to retrieve. - Format: - ``projects/{project}/locations/{location}/triggers/{trigger}`` - body (google.api.httpbody_pb2.HttpBody): - HTTP request body. - project_id (str): - Project in which the specified trigger lives - trigger (str): - Name of the trigger to run the payload - against - secret (str): - Secret token used for authorization if an - OAuth token isn't provided. - """ - - name = proto.Field( - proto.STRING, - number=5, - ) - body = proto.Field( - proto.MESSAGE, - number=1, - message=httpbody_pb2.HttpBody, - ) - project_id = proto.Field( - proto.STRING, - number=2, - ) - trigger = proto.Field( - proto.STRING, - number=3, - ) - secret = proto.Field( - proto.STRING, - number=4, - ) - - -class ReceiveTriggerWebhookResponse(proto.Message): - r"""ReceiveTriggerWebhookResponse [Experimental] is the response object - for the ReceiveTriggerWebhook method. - """ - - -class WorkerPool(proto.Message): - r"""Configuration for a ``WorkerPool``. - - Cloud Build owns and maintains a pool of workers for general use and - have no access to a project's private network. By default, builds - submitted to Cloud Build will use a worker from this pool. - - If your build needs access to resources on a private network, create - and use a ``WorkerPool`` to run your builds. Private - ``WorkerPool``\ s give your builds access to any single VPC network - that you administer, including any on-prem resources connected to - that VPC network. For an overview of private pools, see `Private - pools - overview `__. - - Attributes: - name (str): - Output only. The resource name of the ``WorkerPool``, with - format - ``projects/{project}/locations/{location}/workerPools/{worker_pool}``. - The value of ``{worker_pool}`` is provided by - ``worker_pool_id`` in ``CreateWorkerPool`` request and the - value of ``{location}`` is determined by the endpoint - accessed. - display_name (str): - A user-specified, human-readable name for the - ``WorkerPool``. If provided, this value must be 1-63 - characters. - uid (str): - Output only. A unique identifier for the ``WorkerPool``. - annotations (Sequence[google.devtools.cloudbuild_v1.types.WorkerPool.AnnotationsEntry]): - User specified annotations. See - https://google.aip.dev/128#annotations for more - details such as format and size limitations. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time at which the request to create the - ``WorkerPool`` was received. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time at which the request to update the - ``WorkerPool`` was received. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time at which the request to delete the - ``WorkerPool`` was received. - state (google.devtools.cloudbuild_v1.types.WorkerPool.State): - Output only. ``WorkerPool`` state. - private_pool_v1_config (google.devtools.cloudbuild_v1.types.PrivatePoolV1Config): - Private Pool using a v1 configuration. - etag (str): - Output only. Checksum computed by the server. - May be sent on update and delete requests to - ensure that the client has an up-to-date value - before proceeding. - """ - class State(proto.Enum): - r"""State of the ``WorkerPool``.""" - STATE_UNSPECIFIED = 0 - CREATING = 1 - RUNNING = 2 - DELETING = 3 - DELETED = 4 - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - uid = proto.Field( - proto.STRING, - number=3, - ) - annotations = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - create_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - delete_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - state = proto.Field( - proto.ENUM, - number=8, - enum=State, - ) - private_pool_v1_config = proto.Field( - proto.MESSAGE, - number=12, - oneof='config', - message='PrivatePoolV1Config', - ) - etag = proto.Field( - proto.STRING, - number=11, - ) - - -class PrivatePoolV1Config(proto.Message): - r"""Configuration for a V1 ``PrivatePool``. - Attributes: - worker_config (google.devtools.cloudbuild_v1.types.PrivatePoolV1Config.WorkerConfig): - Machine configuration for the workers in the - pool. - network_config (google.devtools.cloudbuild_v1.types.PrivatePoolV1Config.NetworkConfig): - Network configuration for the pool. - """ - - class WorkerConfig(proto.Message): - r"""Defines the configuration to be used for creating workers in - the pool. - - Attributes: - machine_type (str): - Machine type of a worker, such as ``e2-medium``. See `Worker - pool config - file `__. - If left blank, Cloud Build will use a sensible default. - disk_size_gb (int): - Size of the disk attached to the worker, in GB. See `Worker - pool config - file `__. - Specify a value of up to 1000. If ``0`` is specified, Cloud - Build will use a standard disk size. - """ - - machine_type = proto.Field( - proto.STRING, - number=1, - ) - disk_size_gb = proto.Field( - proto.INT64, - number=2, - ) - - class NetworkConfig(proto.Message): - r"""Defines the network configuration for the pool. - Attributes: - peered_network (str): - Required. Immutable. The network definition that the workers - are peered to. If this section is left empty, the workers - will be peered to ``WorkerPool.project_id`` on the service - producer network. Must be in the format - ``projects/{project}/global/networks/{network}``, where - ``{project}`` is a project number, such as ``12345``, and - ``{network}`` is the name of a VPC network in the project. - See `Understanding network configuration - options `__ - egress_option (google.devtools.cloudbuild_v1.types.PrivatePoolV1Config.NetworkConfig.EgressOption): - Option to configure network egress for the - workers. - """ - class EgressOption(proto.Enum): - r"""Defines the egress option for the pool.""" - EGRESS_OPTION_UNSPECIFIED = 0 - NO_PUBLIC_EGRESS = 1 - PUBLIC_EGRESS = 2 - - peered_network = proto.Field( - proto.STRING, - number=1, - ) - egress_option = proto.Field( - proto.ENUM, - number=2, - enum='PrivatePoolV1Config.NetworkConfig.EgressOption', - ) - - worker_config = proto.Field( - proto.MESSAGE, - number=1, - message=WorkerConfig, - ) - network_config = proto.Field( - proto.MESSAGE, - number=2, - message=NetworkConfig, - ) - - -class CreateWorkerPoolRequest(proto.Message): - r"""Request to create a new ``WorkerPool``. - Attributes: - parent (str): - Required. The parent resource where this worker pool will be - created. Format: - ``projects/{project}/locations/{location}``. - worker_pool (google.devtools.cloudbuild_v1.types.WorkerPool): - Required. ``WorkerPool`` resource to create. - worker_pool_id (str): - Required. Immutable. The ID to use for the ``WorkerPool``, - which will become the final component of the resource name. - - This value should be 1-63 characters, and valid characters - are /[a-z][0-9]-/. - validate_only (bool): - If set, validate the request and preview the - response, but do not actually post it. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - worker_pool = proto.Field( - proto.MESSAGE, - number=2, - message='WorkerPool', - ) - worker_pool_id = proto.Field( - proto.STRING, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetWorkerPoolRequest(proto.Message): - r"""Request to get a ``WorkerPool`` with the specified name. - Attributes: - name (str): - Required. The name of the ``WorkerPool`` to retrieve. - Format: - ``projects/{project}/locations/{location}/workerPools/{workerPool}``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteWorkerPoolRequest(proto.Message): - r"""Request to delete a ``WorkerPool``. - Attributes: - name (str): - Required. The name of the ``WorkerPool`` to delete. Format: - ``projects/{project}/locations/{workerPool}/workerPools/{workerPool}``. - etag (str): - Optional. If this is provided, it must match - the server's etag on the workerpool for the - request to be processed. - allow_missing (bool): - If set to true, and the ``WorkerPool`` is not found, the - request will succeed but no action will be taken on the - server. - validate_only (bool): - If set, validate the request and preview the - response, but do not actually post it. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - etag = proto.Field( - proto.STRING, - number=2, - ) - allow_missing = proto.Field( - proto.BOOL, - number=3, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkerPoolRequest(proto.Message): - r"""Request to update a ``WorkerPool``. - Attributes: - worker_pool (google.devtools.cloudbuild_v1.types.WorkerPool): - Required. The ``WorkerPool`` to update. - - The ``name`` field is used to identify the ``WorkerPool`` to - update. Format: - ``projects/{project}/locations/{location}/workerPools/{workerPool}``. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - A mask specifying which fields in ``worker_pool`` to update. - validate_only (bool): - If set, validate the request and preview the - response, but do not actually post it. - """ - - worker_pool = proto.Field( - proto.MESSAGE, - number=1, - message='WorkerPool', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only = proto.Field( - proto.BOOL, - number=4, - ) - - -class ListWorkerPoolsRequest(proto.Message): - r"""Request to list ``WorkerPool``\ s. - Attributes: - parent (str): - Required. The parent of the collection of ``WorkerPools``. - Format: ``projects/{project}/locations/{location}``. - page_size (int): - The maximum number of ``WorkerPool``\ s to return. The - service may return fewer than this value. If omitted, the - server will use a sensible default. - page_token (str): - A page token, received from a previous ``ListWorkerPools`` - call. Provide this to retrieve the subsequent page. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListWorkerPoolsResponse(proto.Message): - r"""Response containing existing ``WorkerPools``. - Attributes: - worker_pools (Sequence[google.devtools.cloudbuild_v1.types.WorkerPool]): - ``WorkerPools`` for the specified project. - next_page_token (str): - Continuation token used to page through large - result sets. Provide this value in a subsequent - ListWorkerPoolsRequest to return the next page - of results. - """ - - @property - def raw_page(self): - return self - - worker_pools = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkerPool', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateWorkerPoolOperationMetadata(proto.Message): - r"""Metadata for the ``CreateWorkerPool`` operation. - Attributes: - worker_pool (str): - The resource name of the ``WorkerPool`` to create. Format: - ``projects/{project}/locations/{location}/workerPools/{worker_pool}``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Time the operation was created. - complete_time (google.protobuf.timestamp_pb2.Timestamp): - Time the operation was completed. - """ - - worker_pool = proto.Field( - proto.STRING, - number=1, - ) - create_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - complete_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class UpdateWorkerPoolOperationMetadata(proto.Message): - r"""Metadata for the ``UpdateWorkerPool`` operation. - Attributes: - worker_pool (str): - The resource name of the ``WorkerPool`` being updated. - Format: - ``projects/{project}/locations/{location}/workerPools/{worker_pool}``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Time the operation was created. - complete_time (google.protobuf.timestamp_pb2.Timestamp): - Time the operation was completed. - """ - - worker_pool = proto.Field( - proto.STRING, - number=1, - ) - create_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - complete_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class DeleteWorkerPoolOperationMetadata(proto.Message): - r"""Metadata for the ``DeleteWorkerPool`` operation. - Attributes: - worker_pool (str): - The resource name of the ``WorkerPool`` being deleted. - Format: - ``projects/{project}/locations/{location}/workerPools/{worker_pool}``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Time the operation was created. - complete_time (google.protobuf.timestamp_pb2.Timestamp): - Time the operation was completed. - """ - - worker_pool = proto.Field( - proto.STRING, - number=1, - ) - create_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - complete_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 213c014a..00000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/devtools/cloudbuild_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1/scripts/fixup_cloudbuild_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_cloudbuild_v1_keywords.py deleted file mode 100644 index 99a089f1..00000000 --- a/owl-bot-staging/v1/scripts/fixup_cloudbuild_v1_keywords.py +++ /dev/null @@ -1,192 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class cloudbuildCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'cancel_build': ('project_id', 'id', 'name', ), - 'create_build': ('project_id', 'build', 'parent', ), - 'create_build_trigger': ('project_id', 'trigger', 'parent', ), - 'create_worker_pool': ('parent', 'worker_pool', 'worker_pool_id', 'validate_only', ), - 'delete_build_trigger': ('project_id', 'trigger_id', 'name', ), - 'delete_worker_pool': ('name', 'etag', 'allow_missing', 'validate_only', ), - 'get_build': ('project_id', 'id', 'name', ), - 'get_build_trigger': ('project_id', 'trigger_id', 'name', ), - 'get_worker_pool': ('name', ), - 'list_builds': ('project_id', 'parent', 'page_size', 'page_token', 'filter', ), - 'list_build_triggers': ('project_id', 'parent', 'page_size', 'page_token', ), - 'list_worker_pools': ('parent', 'page_size', 'page_token', ), - 'receive_trigger_webhook': ('name', 'body', 'project_id', 'trigger', 'secret', ), - 'retry_build': ('project_id', 'id', 'name', ), - 'run_build_trigger': ('project_id', 'trigger_id', 'name', 'source', ), - 'update_build_trigger': ('project_id', 'trigger_id', 'trigger', ), - 'update_worker_pool': ('worker_pool', 'update_mask', 'validate_only', ), - } - - 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: not a.keyword.value 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=cloudbuildCallTransformer(), -): - """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 cloudbuild 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 5450e820..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-devtools-cloudbuild', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.devtools'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py b/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py deleted file mode 100644 index 029c0ef3..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py +++ /dev/null @@ -1,5062 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.devtools.cloudbuild_v1.services.cloud_build import CloudBuildAsyncClient -from google.devtools.cloudbuild_v1.services.cloud_build import CloudBuildClient -from google.devtools.cloudbuild_v1.services.cloud_build import pagers -from google.devtools.cloudbuild_v1.services.cloud_build import transports -from google.devtools.cloudbuild_v1.services.cloud_build.transports.base import _GOOGLE_AUTH_VERSION -from google.devtools.cloudbuild_v1.types import cloudbuild -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CloudBuildClient._get_default_mtls_endpoint(None) is None - assert CloudBuildClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CloudBuildClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CloudBuildClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CloudBuildClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CloudBuildClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - CloudBuildClient, - CloudBuildAsyncClient, -]) -def test_cloud_build_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudbuild.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CloudBuildGrpcTransport, "grpc"), - (transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_cloud_build_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", [ - CloudBuildClient, - CloudBuildAsyncClient, -]) -def test_cloud_build_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudbuild.googleapis.com:443' - - -def test_cloud_build_client_get_transport_class(): - transport = CloudBuildClient.get_transport_class() - available_transports = [ - transports.CloudBuildGrpcTransport, - ] - assert transport in available_transports - - transport = CloudBuildClient.get_transport_class("grpc") - assert transport == transports.CloudBuildGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudBuildClient, transports.CloudBuildGrpcTransport, "grpc"), - (CloudBuildAsyncClient, transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CloudBuildClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudBuildClient)) -@mock.patch.object(CloudBuildAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudBuildAsyncClient)) -def test_cloud_build_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(CloudBuildClient, '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(CloudBuildClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CloudBuildClient, transports.CloudBuildGrpcTransport, "grpc", "true"), - (CloudBuildAsyncClient, transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CloudBuildClient, transports.CloudBuildGrpcTransport, "grpc", "false"), - (CloudBuildAsyncClient, transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CloudBuildClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudBuildClient)) -@mock.patch.object(CloudBuildAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudBuildAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_cloud_build_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudBuildClient, transports.CloudBuildGrpcTransport, "grpc"), - (CloudBuildAsyncClient, transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_cloud_build_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudBuildClient, transports.CloudBuildGrpcTransport, "grpc"), - (CloudBuildAsyncClient, transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_cloud_build_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_cloud_build_client_client_options_from_dict(): - with mock.patch('google.devtools.cloudbuild_v1.services.cloud_build.transports.CloudBuildGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CloudBuildClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_create_build(transport: str = 'grpc', request_type=cloudbuild.CreateBuildRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_build(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CreateBuildRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_build_from_dict(): - test_create_build(request_type=dict) - - -def test_create_build_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 = CloudBuildClient( - 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_build), - '__call__') as call: - client.create_build() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CreateBuildRequest() - - -@pytest.mark.asyncio -async def test_create_build_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.CreateBuildRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build), - '__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_build(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CreateBuildRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_build_async_from_dict(): - await test_create_build_async(request_type=dict) - - -def test_create_build_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_build), - '__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_build( - project_id='project_id_value', - build=cloudbuild.Build(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].build == cloudbuild.Build(name='name_value') - - -def test_create_build_flattened_error(): - client = CloudBuildClient( - 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_build( - cloudbuild.CreateBuildRequest(), - project_id='project_id_value', - build=cloudbuild.Build(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_build_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_build), - '__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_build( - project_id='project_id_value', - build=cloudbuild.Build(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].build == cloudbuild.Build(name='name_value') - - -@pytest.mark.asyncio -async def test_create_build_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_build( - cloudbuild.CreateBuildRequest(), - project_id='project_id_value', - build=cloudbuild.Build(name='name_value'), - ) - - -def test_get_build(transport: str = 'grpc', request_type=cloudbuild.GetBuildRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.Build( - name='name_value', - id='id_value', - project_id='project_id_value', - status=cloudbuild.Build.Status.QUEUED, - status_detail='status_detail_value', - images=['images_value'], - logs_bucket='logs_bucket_value', - build_trigger_id='build_trigger_id_value', - log_url='log_url_value', - tags=['tags_value'], - service_account='service_account_value', - ) - response = client.get_build(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.GetBuildRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.Build) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.project_id == 'project_id_value' - assert response.status == cloudbuild.Build.Status.QUEUED - assert response.status_detail == 'status_detail_value' - assert response.images == ['images_value'] - assert response.logs_bucket == 'logs_bucket_value' - assert response.build_trigger_id == 'build_trigger_id_value' - assert response.log_url == 'log_url_value' - assert response.tags == ['tags_value'] - assert response.service_account == 'service_account_value' - - -def test_get_build_from_dict(): - test_get_build(request_type=dict) - - -def test_get_build_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 = CloudBuildClient( - 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_build), - '__call__') as call: - client.get_build() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.GetBuildRequest() - - -@pytest.mark.asyncio -async def test_get_build_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.GetBuildRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.Build( - name='name_value', - id='id_value', - project_id='project_id_value', - status=cloudbuild.Build.Status.QUEUED, - status_detail='status_detail_value', - images=['images_value'], - logs_bucket='logs_bucket_value', - build_trigger_id='build_trigger_id_value', - log_url='log_url_value', - tags=['tags_value'], - service_account='service_account_value', - )) - response = await client.get_build(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.GetBuildRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.Build) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.project_id == 'project_id_value' - assert response.status == cloudbuild.Build.Status.QUEUED - assert response.status_detail == 'status_detail_value' - assert response.images == ['images_value'] - assert response.logs_bucket == 'logs_bucket_value' - assert response.build_trigger_id == 'build_trigger_id_value' - assert response.log_url == 'log_url_value' - assert response.tags == ['tags_value'] - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_get_build_async_from_dict(): - await test_get_build_async(request_type=dict) - - -def test_get_build_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_build), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.Build() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_build( - project_id='project_id_value', - id='id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].id == 'id_value' - - -def test_get_build_flattened_error(): - client = CloudBuildClient( - 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_build( - cloudbuild.GetBuildRequest(), - project_id='project_id_value', - id='id_value', - ) - - -@pytest.mark.asyncio -async def test_get_build_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_build), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.Build() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.Build()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_build( - project_id='project_id_value', - id='id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].id == 'id_value' - - -@pytest.mark.asyncio -async def test_get_build_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_build( - cloudbuild.GetBuildRequest(), - project_id='project_id_value', - id='id_value', - ) - - -def test_list_builds(transport: str = 'grpc', request_type=cloudbuild.ListBuildsRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_builds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.ListBuildsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_builds(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ListBuildsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBuildsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_builds_from_dict(): - test_list_builds(request_type=dict) - - -def test_list_builds_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 = CloudBuildClient( - 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_builds), - '__call__') as call: - client.list_builds() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ListBuildsRequest() - - -@pytest.mark.asyncio -async def test_list_builds_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.ListBuildsRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_builds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListBuildsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_builds(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ListBuildsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBuildsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_builds_async_from_dict(): - await test_list_builds_async(request_type=dict) - - -def test_list_builds_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_builds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.ListBuildsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_builds( - project_id='project_id_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].filter == 'filter_value' - - -def test_list_builds_flattened_error(): - client = CloudBuildClient( - 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_builds( - cloudbuild.ListBuildsRequest(), - project_id='project_id_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_builds_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_builds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.ListBuildsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListBuildsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_builds( - project_id='project_id_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_builds_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_builds( - cloudbuild.ListBuildsRequest(), - project_id='project_id_value', - filter='filter_value', - ) - - -def test_list_builds_pager(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_builds), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - cloudbuild.Build(), - cloudbuild.Build(), - ], - next_page_token='abc', - ), - cloudbuild.ListBuildsResponse( - builds=[], - next_page_token='def', - ), - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - ], - next_page_token='ghi', - ), - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - cloudbuild.Build(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.list_builds(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, cloudbuild.Build) - for i in results) - -def test_list_builds_pages(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_builds), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - cloudbuild.Build(), - cloudbuild.Build(), - ], - next_page_token='abc', - ), - cloudbuild.ListBuildsResponse( - builds=[], - next_page_token='def', - ), - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - ], - next_page_token='ghi', - ), - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - cloudbuild.Build(), - ], - ), - RuntimeError, - ) - pages = list(client.list_builds(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_builds_async_pager(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_builds), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - cloudbuild.Build(), - cloudbuild.Build(), - ], - next_page_token='abc', - ), - cloudbuild.ListBuildsResponse( - builds=[], - next_page_token='def', - ), - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - ], - next_page_token='ghi', - ), - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - cloudbuild.Build(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_builds(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, cloudbuild.Build) - for i in responses) - -@pytest.mark.asyncio -async def test_list_builds_async_pages(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_builds), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - cloudbuild.Build(), - cloudbuild.Build(), - ], - next_page_token='abc', - ), - cloudbuild.ListBuildsResponse( - builds=[], - next_page_token='def', - ), - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - ], - next_page_token='ghi', - ), - cloudbuild.ListBuildsResponse( - builds=[ - cloudbuild.Build(), - cloudbuild.Build(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_builds(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_cancel_build(transport: str = 'grpc', request_type=cloudbuild.CancelBuildRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_build), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.Build( - name='name_value', - id='id_value', - project_id='project_id_value', - status=cloudbuild.Build.Status.QUEUED, - status_detail='status_detail_value', - images=['images_value'], - logs_bucket='logs_bucket_value', - build_trigger_id='build_trigger_id_value', - log_url='log_url_value', - tags=['tags_value'], - service_account='service_account_value', - ) - response = client.cancel_build(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CancelBuildRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.Build) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.project_id == 'project_id_value' - assert response.status == cloudbuild.Build.Status.QUEUED - assert response.status_detail == 'status_detail_value' - assert response.images == ['images_value'] - assert response.logs_bucket == 'logs_bucket_value' - assert response.build_trigger_id == 'build_trigger_id_value' - assert response.log_url == 'log_url_value' - assert response.tags == ['tags_value'] - assert response.service_account == 'service_account_value' - - -def test_cancel_build_from_dict(): - test_cancel_build(request_type=dict) - - -def test_cancel_build_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 = CloudBuildClient( - 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.cancel_build), - '__call__') as call: - client.cancel_build() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CancelBuildRequest() - - -@pytest.mark.asyncio -async def test_cancel_build_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.CancelBuildRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_build), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.Build( - name='name_value', - id='id_value', - project_id='project_id_value', - status=cloudbuild.Build.Status.QUEUED, - status_detail='status_detail_value', - images=['images_value'], - logs_bucket='logs_bucket_value', - build_trigger_id='build_trigger_id_value', - log_url='log_url_value', - tags=['tags_value'], - service_account='service_account_value', - )) - response = await client.cancel_build(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CancelBuildRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.Build) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.project_id == 'project_id_value' - assert response.status == cloudbuild.Build.Status.QUEUED - assert response.status_detail == 'status_detail_value' - assert response.images == ['images_value'] - assert response.logs_bucket == 'logs_bucket_value' - assert response.build_trigger_id == 'build_trigger_id_value' - assert response.log_url == 'log_url_value' - assert response.tags == ['tags_value'] - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_cancel_build_async_from_dict(): - await test_cancel_build_async(request_type=dict) - - -def test_cancel_build_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_build), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.Build() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.cancel_build( - project_id='project_id_value', - id='id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].id == 'id_value' - - -def test_cancel_build_flattened_error(): - client = CloudBuildClient( - 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.cancel_build( - cloudbuild.CancelBuildRequest(), - project_id='project_id_value', - id='id_value', - ) - - -@pytest.mark.asyncio -async def test_cancel_build_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_build), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.Build() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.Build()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.cancel_build( - project_id='project_id_value', - id='id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].id == 'id_value' - - -@pytest.mark.asyncio -async def test_cancel_build_flattened_error_async(): - client = CloudBuildAsyncClient( - 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.cancel_build( - cloudbuild.CancelBuildRequest(), - project_id='project_id_value', - id='id_value', - ) - - -def test_retry_build(transport: str = 'grpc', request_type=cloudbuild.RetryBuildRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retry_build), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.retry_build(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.RetryBuildRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_retry_build_from_dict(): - test_retry_build(request_type=dict) - - -def test_retry_build_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 = CloudBuildClient( - 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.retry_build), - '__call__') as call: - client.retry_build() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.RetryBuildRequest() - - -@pytest.mark.asyncio -async def test_retry_build_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.RetryBuildRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retry_build), - '__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.retry_build(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.RetryBuildRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_retry_build_async_from_dict(): - await test_retry_build_async(request_type=dict) - - -def test_retry_build_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retry_build), - '__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.retry_build( - project_id='project_id_value', - id='id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].id == 'id_value' - - -def test_retry_build_flattened_error(): - client = CloudBuildClient( - 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.retry_build( - cloudbuild.RetryBuildRequest(), - project_id='project_id_value', - id='id_value', - ) - - -@pytest.mark.asyncio -async def test_retry_build_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retry_build), - '__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.retry_build( - project_id='project_id_value', - id='id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].id == 'id_value' - - -@pytest.mark.asyncio -async def test_retry_build_flattened_error_async(): - client = CloudBuildAsyncClient( - 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.retry_build( - cloudbuild.RetryBuildRequest(), - project_id='project_id_value', - id='id_value', - ) - - -def test_create_build_trigger(transport: str = 'grpc', request_type=cloudbuild.CreateBuildTriggerRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.BuildTrigger( - resource_name='resource_name_value', - id='id_value', - description='description_value', - name='name_value', - tags=['tags_value'], - disabled=True, - ignored_files=['ignored_files_value'], - included_files=['included_files_value'], - filter='filter_value', - autodetect=True, - ) - response = client.create_build_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CreateBuildTriggerRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.BuildTrigger) - assert response.resource_name == 'resource_name_value' - assert response.id == 'id_value' - assert response.description == 'description_value' - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.disabled is True - assert response.ignored_files == ['ignored_files_value'] - assert response.included_files == ['included_files_value'] - assert response.filter == 'filter_value' - - -def test_create_build_trigger_from_dict(): - test_create_build_trigger(request_type=dict) - - -def test_create_build_trigger_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 = CloudBuildClient( - 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_build_trigger), - '__call__') as call: - client.create_build_trigger() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CreateBuildTriggerRequest() - - -@pytest.mark.asyncio -async def test_create_build_trigger_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.CreateBuildTriggerRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger( - resource_name='resource_name_value', - id='id_value', - description='description_value', - name='name_value', - tags=['tags_value'], - disabled=True, - ignored_files=['ignored_files_value'], - included_files=['included_files_value'], - filter='filter_value', - )) - response = await client.create_build_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CreateBuildTriggerRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.BuildTrigger) - assert response.resource_name == 'resource_name_value' - assert response.id == 'id_value' - assert response.description == 'description_value' - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.disabled is True - assert response.ignored_files == ['ignored_files_value'] - assert response.included_files == ['included_files_value'] - assert response.filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_create_build_trigger_async_from_dict(): - await test_create_build_trigger_async(request_type=dict) - - -def test_create_build_trigger_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.BuildTrigger() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_build_trigger( - project_id='project_id_value', - trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].trigger == cloudbuild.BuildTrigger(resource_name='resource_name_value') - - -def test_create_build_trigger_flattened_error(): - client = CloudBuildClient( - 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_build_trigger( - cloudbuild.CreateBuildTriggerRequest(), - project_id='project_id_value', - trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_build_trigger_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.BuildTrigger() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_build_trigger( - project_id='project_id_value', - trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].trigger == cloudbuild.BuildTrigger(resource_name='resource_name_value') - - -@pytest.mark.asyncio -async def test_create_build_trigger_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_build_trigger( - cloudbuild.CreateBuildTriggerRequest(), - project_id='project_id_value', - trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), - ) - - -def test_get_build_trigger(transport: str = 'grpc', request_type=cloudbuild.GetBuildTriggerRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.BuildTrigger( - resource_name='resource_name_value', - id='id_value', - description='description_value', - name='name_value', - tags=['tags_value'], - disabled=True, - ignored_files=['ignored_files_value'], - included_files=['included_files_value'], - filter='filter_value', - autodetect=True, - ) - response = client.get_build_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.GetBuildTriggerRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.BuildTrigger) - assert response.resource_name == 'resource_name_value' - assert response.id == 'id_value' - assert response.description == 'description_value' - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.disabled is True - assert response.ignored_files == ['ignored_files_value'] - assert response.included_files == ['included_files_value'] - assert response.filter == 'filter_value' - - -def test_get_build_trigger_from_dict(): - test_get_build_trigger(request_type=dict) - - -def test_get_build_trigger_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 = CloudBuildClient( - 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_build_trigger), - '__call__') as call: - client.get_build_trigger() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.GetBuildTriggerRequest() - - -@pytest.mark.asyncio -async def test_get_build_trigger_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.GetBuildTriggerRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger( - resource_name='resource_name_value', - id='id_value', - description='description_value', - name='name_value', - tags=['tags_value'], - disabled=True, - ignored_files=['ignored_files_value'], - included_files=['included_files_value'], - filter='filter_value', - )) - response = await client.get_build_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.GetBuildTriggerRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.BuildTrigger) - assert response.resource_name == 'resource_name_value' - assert response.id == 'id_value' - assert response.description == 'description_value' - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.disabled is True - assert response.ignored_files == ['ignored_files_value'] - assert response.included_files == ['included_files_value'] - assert response.filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_get_build_trigger_async_from_dict(): - await test_get_build_trigger_async(request_type=dict) - - -def test_get_build_trigger_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.BuildTrigger() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_build_trigger( - project_id='project_id_value', - trigger_id='trigger_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].trigger_id == 'trigger_id_value' - - -def test_get_build_trigger_flattened_error(): - client = CloudBuildClient( - 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_build_trigger( - cloudbuild.GetBuildTriggerRequest(), - project_id='project_id_value', - trigger_id='trigger_id_value', - ) - - -@pytest.mark.asyncio -async def test_get_build_trigger_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.BuildTrigger() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_build_trigger( - project_id='project_id_value', - trigger_id='trigger_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].trigger_id == 'trigger_id_value' - - -@pytest.mark.asyncio -async def test_get_build_trigger_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_build_trigger( - cloudbuild.GetBuildTriggerRequest(), - project_id='project_id_value', - trigger_id='trigger_id_value', - ) - - -def test_list_build_triggers(transport: str = 'grpc', request_type=cloudbuild.ListBuildTriggersRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build_triggers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.ListBuildTriggersResponse( - next_page_token='next_page_token_value', - ) - response = client.list_build_triggers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ListBuildTriggersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBuildTriggersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_build_triggers_from_dict(): - test_list_build_triggers(request_type=dict) - - -def test_list_build_triggers_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 = CloudBuildClient( - 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_build_triggers), - '__call__') as call: - client.list_build_triggers() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ListBuildTriggersRequest() - - -@pytest.mark.asyncio -async def test_list_build_triggers_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.ListBuildTriggersRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build_triggers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListBuildTriggersResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_build_triggers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ListBuildTriggersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBuildTriggersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_build_triggers_async_from_dict(): - await test_list_build_triggers_async(request_type=dict) - - -def test_list_build_triggers_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_build_triggers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.ListBuildTriggersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_build_triggers( - project_id='project_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - - -def test_list_build_triggers_flattened_error(): - client = CloudBuildClient( - 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_build_triggers( - cloudbuild.ListBuildTriggersRequest(), - project_id='project_id_value', - ) - - -@pytest.mark.asyncio -async def test_list_build_triggers_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_build_triggers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.ListBuildTriggersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListBuildTriggersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_build_triggers( - project_id='project_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - - -@pytest.mark.asyncio -async def test_list_build_triggers_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_build_triggers( - cloudbuild.ListBuildTriggersRequest(), - project_id='project_id_value', - ) - - -def test_list_build_triggers_pager(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_build_triggers), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - ], - next_page_token='abc', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[], - next_page_token='def', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - ], - next_page_token='ghi', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.list_build_triggers(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, cloudbuild.BuildTrigger) - for i in results) - -def test_list_build_triggers_pages(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_build_triggers), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - ], - next_page_token='abc', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[], - next_page_token='def', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - ], - next_page_token='ghi', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - ], - ), - RuntimeError, - ) - pages = list(client.list_build_triggers(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_build_triggers_async_pager(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_build_triggers), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - ], - next_page_token='abc', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[], - next_page_token='def', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - ], - next_page_token='ghi', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_build_triggers(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, cloudbuild.BuildTrigger) - for i in responses) - -@pytest.mark.asyncio -async def test_list_build_triggers_async_pages(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_build_triggers), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - ], - next_page_token='abc', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[], - next_page_token='def', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - ], - next_page_token='ghi', - ), - cloudbuild.ListBuildTriggersResponse( - triggers=[ - cloudbuild.BuildTrigger(), - cloudbuild.BuildTrigger(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_build_triggers(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_delete_build_trigger(transport: str = 'grpc', request_type=cloudbuild.DeleteBuildTriggerRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_build_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.DeleteBuildTriggerRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_build_trigger_from_dict(): - test_delete_build_trigger(request_type=dict) - - -def test_delete_build_trigger_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 = CloudBuildClient( - 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_build_trigger), - '__call__') as call: - client.delete_build_trigger() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.DeleteBuildTriggerRequest() - - -@pytest.mark.asyncio -async def test_delete_build_trigger_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.DeleteBuildTriggerRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_build_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.DeleteBuildTriggerRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_build_trigger_async_from_dict(): - await test_delete_build_trigger_async(request_type=dict) - - -def test_delete_build_trigger_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_build_trigger( - project_id='project_id_value', - trigger_id='trigger_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].trigger_id == 'trigger_id_value' - - -def test_delete_build_trigger_flattened_error(): - client = CloudBuildClient( - 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_build_trigger( - cloudbuild.DeleteBuildTriggerRequest(), - project_id='project_id_value', - trigger_id='trigger_id_value', - ) - - -@pytest.mark.asyncio -async def test_delete_build_trigger_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_build_trigger( - project_id='project_id_value', - trigger_id='trigger_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].trigger_id == 'trigger_id_value' - - -@pytest.mark.asyncio -async def test_delete_build_trigger_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_build_trigger( - cloudbuild.DeleteBuildTriggerRequest(), - project_id='project_id_value', - trigger_id='trigger_id_value', - ) - - -def test_update_build_trigger(transport: str = 'grpc', request_type=cloudbuild.UpdateBuildTriggerRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.BuildTrigger( - resource_name='resource_name_value', - id='id_value', - description='description_value', - name='name_value', - tags=['tags_value'], - disabled=True, - ignored_files=['ignored_files_value'], - included_files=['included_files_value'], - filter='filter_value', - autodetect=True, - ) - response = client.update_build_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.UpdateBuildTriggerRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.BuildTrigger) - assert response.resource_name == 'resource_name_value' - assert response.id == 'id_value' - assert response.description == 'description_value' - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.disabled is True - assert response.ignored_files == ['ignored_files_value'] - assert response.included_files == ['included_files_value'] - assert response.filter == 'filter_value' - - -def test_update_build_trigger_from_dict(): - test_update_build_trigger(request_type=dict) - - -def test_update_build_trigger_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 = CloudBuildClient( - 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_build_trigger), - '__call__') as call: - client.update_build_trigger() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.UpdateBuildTriggerRequest() - - -@pytest.mark.asyncio -async def test_update_build_trigger_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.UpdateBuildTriggerRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger( - resource_name='resource_name_value', - id='id_value', - description='description_value', - name='name_value', - tags=['tags_value'], - disabled=True, - ignored_files=['ignored_files_value'], - included_files=['included_files_value'], - filter='filter_value', - )) - response = await client.update_build_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.UpdateBuildTriggerRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.BuildTrigger) - assert response.resource_name == 'resource_name_value' - assert response.id == 'id_value' - assert response.description == 'description_value' - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.disabled is True - assert response.ignored_files == ['ignored_files_value'] - assert response.included_files == ['included_files_value'] - assert response.filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_update_build_trigger_async_from_dict(): - await test_update_build_trigger_async(request_type=dict) - - -def test_update_build_trigger_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.BuildTrigger() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_build_trigger( - project_id='project_id_value', - trigger_id='trigger_id_value', - trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].trigger_id == 'trigger_id_value' - assert args[0].trigger == cloudbuild.BuildTrigger(resource_name='resource_name_value') - - -def test_update_build_trigger_flattened_error(): - client = CloudBuildClient( - 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_build_trigger( - cloudbuild.UpdateBuildTriggerRequest(), - project_id='project_id_value', - trigger_id='trigger_id_value', - trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_build_trigger_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.BuildTrigger() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.BuildTrigger()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_build_trigger( - project_id='project_id_value', - trigger_id='trigger_id_value', - trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].trigger_id == 'trigger_id_value' - assert args[0].trigger == cloudbuild.BuildTrigger(resource_name='resource_name_value') - - -@pytest.mark.asyncio -async def test_update_build_trigger_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_build_trigger( - cloudbuild.UpdateBuildTriggerRequest(), - project_id='project_id_value', - trigger_id='trigger_id_value', - trigger=cloudbuild.BuildTrigger(resource_name='resource_name_value'), - ) - - -def test_run_build_trigger(transport: str = 'grpc', request_type=cloudbuild.RunBuildTriggerRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_build_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_build_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.RunBuildTriggerRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_build_trigger_from_dict(): - test_run_build_trigger(request_type=dict) - - -def test_run_build_trigger_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 = CloudBuildClient( - 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.run_build_trigger), - '__call__') as call: - client.run_build_trigger() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.RunBuildTriggerRequest() - - -@pytest.mark.asyncio -async def test_run_build_trigger_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.RunBuildTriggerRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_build_trigger), - '__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.run_build_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.RunBuildTriggerRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_run_build_trigger_async_from_dict(): - await test_run_build_trigger_async(request_type=dict) - - -def test_run_build_trigger_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_build_trigger), - '__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.run_build_trigger( - project_id='project_id_value', - trigger_id='trigger_id_value', - source=cloudbuild.RepoSource(project_id='project_id_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].trigger_id == 'trigger_id_value' - assert args[0].source == cloudbuild.RepoSource(project_id='project_id_value') - - -def test_run_build_trigger_flattened_error(): - client = CloudBuildClient( - 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.run_build_trigger( - cloudbuild.RunBuildTriggerRequest(), - project_id='project_id_value', - trigger_id='trigger_id_value', - source=cloudbuild.RepoSource(project_id='project_id_value'), - ) - - -@pytest.mark.asyncio -async def test_run_build_trigger_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_build_trigger), - '__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.run_build_trigger( - project_id='project_id_value', - trigger_id='trigger_id_value', - source=cloudbuild.RepoSource(project_id='project_id_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].project_id == 'project_id_value' - assert args[0].trigger_id == 'trigger_id_value' - assert args[0].source == cloudbuild.RepoSource(project_id='project_id_value') - - -@pytest.mark.asyncio -async def test_run_build_trigger_flattened_error_async(): - client = CloudBuildAsyncClient( - 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.run_build_trigger( - cloudbuild.RunBuildTriggerRequest(), - project_id='project_id_value', - trigger_id='trigger_id_value', - source=cloudbuild.RepoSource(project_id='project_id_value'), - ) - - -def test_receive_trigger_webhook(transport: str = 'grpc', request_type=cloudbuild.ReceiveTriggerWebhookRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.receive_trigger_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.ReceiveTriggerWebhookResponse( - ) - response = client.receive_trigger_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ReceiveTriggerWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.ReceiveTriggerWebhookResponse) - - -def test_receive_trigger_webhook_from_dict(): - test_receive_trigger_webhook(request_type=dict) - - -def test_receive_trigger_webhook_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 = CloudBuildClient( - 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.receive_trigger_webhook), - '__call__') as call: - client.receive_trigger_webhook() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ReceiveTriggerWebhookRequest() - - -@pytest.mark.asyncio -async def test_receive_trigger_webhook_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.ReceiveTriggerWebhookRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.receive_trigger_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ReceiveTriggerWebhookResponse( - )) - response = await client.receive_trigger_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ReceiveTriggerWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.ReceiveTriggerWebhookResponse) - - -@pytest.mark.asyncio -async def test_receive_trigger_webhook_async_from_dict(): - await test_receive_trigger_webhook_async(request_type=dict) - - -def test_create_worker_pool(transport: str = 'grpc', request_type=cloudbuild.CreateWorkerPoolRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CreateWorkerPoolRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_worker_pool_from_dict(): - test_create_worker_pool(request_type=dict) - - -def test_create_worker_pool_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 = CloudBuildClient( - 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_worker_pool), - '__call__') as call: - client.create_worker_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CreateWorkerPoolRequest() - - -@pytest.mark.asyncio -async def test_create_worker_pool_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.CreateWorkerPoolRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.CreateWorkerPoolRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_worker_pool_async_from_dict(): - await test_create_worker_pool_async(request_type=dict) - - -def test_create_worker_pool_field_headers(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloudbuild.CreateWorkerPoolRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_worker_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_worker_pool_field_headers_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloudbuild.CreateWorkerPoolRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_worker_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_create_worker_pool_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_worker_pool( - parent='parent_value', - worker_pool=cloudbuild.WorkerPool(name='name_value'), - worker_pool_id='worker_pool_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].worker_pool == cloudbuild.WorkerPool(name='name_value') - assert args[0].worker_pool_id == 'worker_pool_id_value' - - -def test_create_worker_pool_flattened_error(): - client = CloudBuildClient( - 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_worker_pool( - cloudbuild.CreateWorkerPoolRequest(), - parent='parent_value', - worker_pool=cloudbuild.WorkerPool(name='name_value'), - worker_pool_id='worker_pool_id_value', - ) - - -@pytest.mark.asyncio -async def test_create_worker_pool_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_worker_pool( - parent='parent_value', - worker_pool=cloudbuild.WorkerPool(name='name_value'), - worker_pool_id='worker_pool_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].worker_pool == cloudbuild.WorkerPool(name='name_value') - assert args[0].worker_pool_id == 'worker_pool_id_value' - - -@pytest.mark.asyncio -async def test_create_worker_pool_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_worker_pool( - cloudbuild.CreateWorkerPoolRequest(), - parent='parent_value', - worker_pool=cloudbuild.WorkerPool(name='name_value'), - worker_pool_id='worker_pool_id_value', - ) - - -def test_get_worker_pool(transport: str = 'grpc', request_type=cloudbuild.GetWorkerPoolRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.WorkerPool( - name='name_value', - display_name='display_name_value', - uid='uid_value', - state=cloudbuild.WorkerPool.State.CREATING, - etag='etag_value', - private_pool_v1_config=cloudbuild.PrivatePoolV1Config(worker_config=cloudbuild.PrivatePoolV1Config.WorkerConfig(machine_type='machine_type_value')), - ) - response = client.get_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.GetWorkerPoolRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.WorkerPool) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.state == cloudbuild.WorkerPool.State.CREATING - assert response.etag == 'etag_value' - - -def test_get_worker_pool_from_dict(): - test_get_worker_pool(request_type=dict) - - -def test_get_worker_pool_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 = CloudBuildClient( - 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_worker_pool), - '__call__') as call: - client.get_worker_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.GetWorkerPoolRequest() - - -@pytest.mark.asyncio -async def test_get_worker_pool_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.GetWorkerPoolRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.WorkerPool( - name='name_value', - display_name='display_name_value', - uid='uid_value', - state=cloudbuild.WorkerPool.State.CREATING, - etag='etag_value', - )) - response = await client.get_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.GetWorkerPoolRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, cloudbuild.WorkerPool) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.state == cloudbuild.WorkerPool.State.CREATING - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_worker_pool_async_from_dict(): - await test_get_worker_pool_async(request_type=dict) - - -def test_get_worker_pool_field_headers(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloudbuild.GetWorkerPoolRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_worker_pool), - '__call__') as call: - call.return_value = cloudbuild.WorkerPool() - client.get_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_worker_pool_field_headers_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloudbuild.GetWorkerPoolRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_worker_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.WorkerPool()) - await client.get_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_worker_pool_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.WorkerPool() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_worker_pool( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_worker_pool_flattened_error(): - client = CloudBuildClient( - 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_worker_pool( - cloudbuild.GetWorkerPoolRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_worker_pool_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.WorkerPool() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.WorkerPool()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_worker_pool( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_worker_pool_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_worker_pool( - cloudbuild.GetWorkerPoolRequest(), - name='name_value', - ) - - -def test_delete_worker_pool(transport: str = 'grpc', request_type=cloudbuild.DeleteWorkerPoolRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.DeleteWorkerPoolRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_worker_pool_from_dict(): - test_delete_worker_pool(request_type=dict) - - -def test_delete_worker_pool_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 = CloudBuildClient( - 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_worker_pool), - '__call__') as call: - client.delete_worker_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.DeleteWorkerPoolRequest() - - -@pytest.mark.asyncio -async def test_delete_worker_pool_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.DeleteWorkerPoolRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.DeleteWorkerPoolRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_worker_pool_async_from_dict(): - await test_delete_worker_pool_async(request_type=dict) - - -def test_delete_worker_pool_field_headers(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloudbuild.DeleteWorkerPoolRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_worker_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_worker_pool_field_headers_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloudbuild.DeleteWorkerPoolRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_worker_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_worker_pool_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_worker_pool( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_delete_worker_pool_flattened_error(): - client = CloudBuildClient( - 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_worker_pool( - cloudbuild.DeleteWorkerPoolRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_worker_pool_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_worker_pool( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_worker_pool_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_worker_pool( - cloudbuild.DeleteWorkerPoolRequest(), - name='name_value', - ) - - -def test_update_worker_pool(transport: str = 'grpc', request_type=cloudbuild.UpdateWorkerPoolRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.UpdateWorkerPoolRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_worker_pool_from_dict(): - test_update_worker_pool(request_type=dict) - - -def test_update_worker_pool_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 = CloudBuildClient( - 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_worker_pool), - '__call__') as call: - client.update_worker_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.UpdateWorkerPoolRequest() - - -@pytest.mark.asyncio -async def test_update_worker_pool_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.UpdateWorkerPoolRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.UpdateWorkerPoolRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_worker_pool_async_from_dict(): - await test_update_worker_pool_async(request_type=dict) - - -def test_update_worker_pool_field_headers(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloudbuild.UpdateWorkerPoolRequest() - - request.worker_pool.name = 'worker_pool.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_worker_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'worker_pool.name=worker_pool.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_worker_pool_field_headers_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloudbuild.UpdateWorkerPoolRequest() - - request.worker_pool.name = 'worker_pool.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_worker_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_worker_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'worker_pool.name=worker_pool.name/value', - ) in kw['metadata'] - - -def test_update_worker_pool_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_worker_pool( - worker_pool=cloudbuild.WorkerPool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].worker_pool == cloudbuild.WorkerPool(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_worker_pool_flattened_error(): - client = CloudBuildClient( - 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_worker_pool( - cloudbuild.UpdateWorkerPoolRequest(), - worker_pool=cloudbuild.WorkerPool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_worker_pool_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_worker_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_worker_pool( - worker_pool=cloudbuild.WorkerPool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].worker_pool == cloudbuild.WorkerPool(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_worker_pool_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_worker_pool( - cloudbuild.UpdateWorkerPoolRequest(), - worker_pool=cloudbuild.WorkerPool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_list_worker_pools(transport: str = 'grpc', request_type=cloudbuild.ListWorkerPoolsRequest): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_worker_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.ListWorkerPoolsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_worker_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ListWorkerPoolsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkerPoolsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_worker_pools_from_dict(): - test_list_worker_pools(request_type=dict) - - -def test_list_worker_pools_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 = CloudBuildClient( - 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_worker_pools), - '__call__') as call: - client.list_worker_pools() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ListWorkerPoolsRequest() - - -@pytest.mark.asyncio -async def test_list_worker_pools_async(transport: str = 'grpc_asyncio', request_type=cloudbuild.ListWorkerPoolsRequest): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_worker_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListWorkerPoolsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_worker_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == cloudbuild.ListWorkerPoolsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkerPoolsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_worker_pools_async_from_dict(): - await test_list_worker_pools_async(request_type=dict) - - -def test_list_worker_pools_field_headers(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloudbuild.ListWorkerPoolsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_worker_pools), - '__call__') as call: - call.return_value = cloudbuild.ListWorkerPoolsResponse() - client.list_worker_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_worker_pools_field_headers_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloudbuild.ListWorkerPoolsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_worker_pools), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListWorkerPoolsResponse()) - await client.list_worker_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_worker_pools_flattened(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_worker_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.ListWorkerPoolsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_worker_pools( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_worker_pools_flattened_error(): - client = CloudBuildClient( - 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_worker_pools( - cloudbuild.ListWorkerPoolsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_worker_pools_flattened_async(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_worker_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloudbuild.ListWorkerPoolsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloudbuild.ListWorkerPoolsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_worker_pools( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_worker_pools_flattened_error_async(): - client = CloudBuildAsyncClient( - 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_worker_pools( - cloudbuild.ListWorkerPoolsRequest(), - parent='parent_value', - ) - - -def test_list_worker_pools_pager(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_worker_pools), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - ], - next_page_token='abc', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[], - next_page_token='def', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - ], - next_page_token='ghi', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_worker_pools(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, cloudbuild.WorkerPool) - for i in results) - -def test_list_worker_pools_pages(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_worker_pools), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - ], - next_page_token='abc', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[], - next_page_token='def', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - ], - next_page_token='ghi', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - ], - ), - RuntimeError, - ) - pages = list(client.list_worker_pools(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_worker_pools_async_pager(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_worker_pools), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - ], - next_page_token='abc', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[], - next_page_token='def', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - ], - next_page_token='ghi', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_worker_pools(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, cloudbuild.WorkerPool) - for i in responses) - -@pytest.mark.asyncio -async def test_list_worker_pools_async_pages(): - client = CloudBuildAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_worker_pools), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - ], - next_page_token='abc', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[], - next_page_token='def', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - ], - next_page_token='ghi', - ), - cloudbuild.ListWorkerPoolsResponse( - worker_pools=[ - cloudbuild.WorkerPool(), - cloudbuild.WorkerPool(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_worker_pools(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CloudBuildGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CloudBuildGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudBuildClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CloudBuildGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudBuildClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudBuildGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CloudBuildClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudBuildGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CloudBuildGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CloudBuildGrpcTransport, - transports.CloudBuildGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CloudBuildGrpcTransport, - ) - -def test_cloud_build_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CloudBuildTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_cloud_build_base_transport(): - # Instantiate the base transport. - with mock.patch('google.devtools.cloudbuild_v1.services.cloud_build.transports.CloudBuildTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CloudBuildTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_build', - 'get_build', - 'list_builds', - 'cancel_build', - 'retry_build', - 'create_build_trigger', - 'get_build_trigger', - 'list_build_triggers', - 'delete_build_trigger', - 'update_build_trigger', - 'run_build_trigger', - 'receive_trigger_webhook', - 'create_worker_pool', - 'get_worker_pool', - 'delete_worker_pool', - 'update_worker_pool', - 'list_worker_pools', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_cloud_build_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.devtools.cloudbuild_v1.services.cloud_build.transports.CloudBuildTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudBuildTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_cloud_build_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.devtools.cloudbuild_v1.services.cloud_build.transports.CloudBuildTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudBuildTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_cloud_build_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.devtools.cloudbuild_v1.services.cloud_build.transports.CloudBuildTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudBuildTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_cloud_build_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) - CloudBuildClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_cloud_build_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CloudBuildClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudBuildGrpcTransport, - transports.CloudBuildGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_cloud_build_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.CloudBuildGrpcTransport, - transports.CloudBuildGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_cloud_build_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CloudBuildGrpcTransport, grpc_helpers), - (transports.CloudBuildGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_cloud_build_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( - "cloudbuild.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="cloudbuild.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CloudBuildGrpcTransport, transports.CloudBuildGrpcAsyncIOTransport]) -def test_cloud_build_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_cloud_build_host_no_port(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudbuild.googleapis.com'), - ) - assert client.transport._host == 'cloudbuild.googleapis.com:443' - - -def test_cloud_build_host_with_port(): - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudbuild.googleapis.com:8000'), - ) - assert client.transport._host == 'cloudbuild.googleapis.com:8000' - -def test_cloud_build_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CloudBuildGrpcTransport( - 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_build_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CloudBuildGrpcAsyncIOTransport( - 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.CloudBuildGrpcTransport, transports.CloudBuildGrpcAsyncIOTransport]) -def test_cloud_build_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.CloudBuildGrpcTransport, transports.CloudBuildGrpcAsyncIOTransport]) -def test_cloud_build_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_build_grpc_lro_client(): - client = CloudBuildClient( - 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_build_grpc_lro_async_client(): - client = CloudBuildAsyncClient( - 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" - build = "clam" - expected = "projects/{project}/builds/{build}".format(project=project, build=build, ) - actual = CloudBuildClient.build_path(project, build) - assert expected == actual - - -def test_parse_build_path(): - expected = { - "project": "whelk", - "build": "octopus", - } - path = CloudBuildClient.build_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_build_path(path) - assert expected == actual - -def test_build_trigger_path(): - project = "oyster" - trigger = "nudibranch" - expected = "projects/{project}/triggers/{trigger}".format(project=project, trigger=trigger, ) - actual = CloudBuildClient.build_trigger_path(project, trigger) - assert expected == actual - - -def test_parse_build_trigger_path(): - expected = { - "project": "cuttlefish", - "trigger": "mussel", - } - path = CloudBuildClient.build_trigger_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_build_trigger_path(path) - assert expected == actual - -def test_crypto_key_path(): - project = "winkle" - location = "nautilus" - keyring = "scallop" - key = "abalone" - expected = "projects/{project}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}".format(project=project, location=location, keyring=keyring, key=key, ) - actual = CloudBuildClient.crypto_key_path(project, location, keyring, key) - assert expected == actual - - -def test_parse_crypto_key_path(): - expected = { - "project": "squid", - "location": "clam", - "keyring": "whelk", - "key": "octopus", - } - path = CloudBuildClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_crypto_key_path(path) - assert expected == actual - -def test_network_path(): - project = "oyster" - network = "nudibranch" - expected = "projects/{project}/global/networks/{network}".format(project=project, network=network, ) - actual = CloudBuildClient.network_path(project, network) - assert expected == actual - - -def test_parse_network_path(): - expected = { - "project": "cuttlefish", - "network": "mussel", - } - path = CloudBuildClient.network_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_network_path(path) - assert expected == actual - -def test_secret_version_path(): - project = "winkle" - secret = "nautilus" - version = "scallop" - expected = "projects/{project}/secrets/{secret}/versions/{version}".format(project=project, secret=secret, version=version, ) - actual = CloudBuildClient.secret_version_path(project, secret, version) - assert expected == actual - - -def test_parse_secret_version_path(): - expected = { - "project": "abalone", - "secret": "squid", - "version": "clam", - } - path = CloudBuildClient.secret_version_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_secret_version_path(path) - assert expected == actual - -def test_service_account_path(): - project = "whelk" - service_account = "octopus" - expected = "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) - actual = CloudBuildClient.service_account_path(project, service_account) - assert expected == actual - - -def test_parse_service_account_path(): - expected = { - "project": "oyster", - "service_account": "nudibranch", - } - path = CloudBuildClient.service_account_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_service_account_path(path) - assert expected == actual - -def test_subscription_path(): - project = "cuttlefish" - subscription = "mussel" - expected = "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) - actual = CloudBuildClient.subscription_path(project, subscription) - assert expected == actual - - -def test_parse_subscription_path(): - expected = { - "project": "winkle", - "subscription": "nautilus", - } - path = CloudBuildClient.subscription_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_subscription_path(path) - assert expected == actual - -def test_topic_path(): - project = "scallop" - topic = "abalone" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = CloudBuildClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "squid", - "topic": "clam", - } - path = CloudBuildClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_topic_path(path) - assert expected == actual - -def test_worker_pool_path(): - project = "whelk" - location = "octopus" - worker_pool = "oyster" - expected = "projects/{project}/locations/{location}/workerPools/{worker_pool}".format(project=project, location=location, worker_pool=worker_pool, ) - actual = CloudBuildClient.worker_pool_path(project, location, worker_pool) - assert expected == actual - - -def test_parse_worker_pool_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "worker_pool": "mussel", - } - path = CloudBuildClient.worker_pool_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_worker_pool_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CloudBuildClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = CloudBuildClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = CloudBuildClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = CloudBuildClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CloudBuildClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = CloudBuildClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = CloudBuildClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = CloudBuildClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.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 = CloudBuildClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = CloudBuildClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CloudBuildClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CloudBuildTransport, '_prep_wrapped_messages') as prep: - client = CloudBuildClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CloudBuildTransport, '_prep_wrapped_messages') as prep: - transport_class = CloudBuildClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py b/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py index e26b4d9b..17a7f18a 100644 --- a/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py +++ b/tests/unit/gapic/cloudbuild_v1/test_cloud_build.py @@ -124,16 +124,6 @@ def test_cloud_build_client_from_service_account_info(client_class): assert client.transport._host == "cloudbuild.googleapis.com:443" -@pytest.mark.parametrize("client_class", [CloudBuildClient, CloudBuildAsyncClient,]) -def test_cloud_build_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -141,7 +131,7 @@ def test_cloud_build_client_service_account_always_use_jwt(client_class): (transports.CloudBuildGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_cloud_build_client_service_account_always_use_jwt_true( +def test_cloud_build_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -151,6 +141,13 @@ def test_cloud_build_client_service_account_always_use_jwt_true( 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", [CloudBuildClient, CloudBuildAsyncClient,]) def test_cloud_build_client_from_service_account_file(client_class): @@ -227,6 +224,7 @@ def test_cloud_build_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -243,6 +241,7 @@ def test_cloud_build_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -259,6 +258,7 @@ def test_cloud_build_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -287,6 +287,7 @@ def test_cloud_build_client_client_options( client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -351,6 +352,7 @@ def test_cloud_build_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -384,6 +386,7 @@ def test_cloud_build_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -405,6 +408,7 @@ def test_cloud_build_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -435,6 +439,7 @@ def test_cloud_build_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -465,6 +470,7 @@ def test_cloud_build_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -482,6 +488,7 @@ def test_cloud_build_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, )